package learning;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
public class IOStreamDemo {
//输入字节流InputStream、输出字节流OutputStream
//输入字符流Reader、输出字符流Writer
//字符流设有缓冲区,对字节(二进制)数据进行处理,因此便于处理中文
//字节流更通用
public static void main(String[] args) throws IOException {
File f=new File("D:"+File.separator+"IOStream"+File.separator+"IO.txt");
if(!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
OutputStream output=new FileOutputStream(f); //通过子类实例化
String str1="test words.";
output.write(str1.getBytes());
output.close();
InputStream input=new FileInputStream(f);
byte[] data=new byte[256];
int len1=input.read(data); //读取数据保存在字节数组中,返回读取的字节个数
System.out.println("["+new String(data,0,len1)+"]");
input.close();
Writer w=new FileWriter(f,true);
String str2="line3\r\n";
w.write(str2);
w.append(str2); //创建Writer时加true、或者用append,从而追加内容
w.close(); //不关闭又要从缓冲区输出,用flush
Reader r=new FileReader(f);
char[] buffer=new char[256];
int len2=r.read(buffer);
System.out.println(new String(buffer,0,len2));
r.close();
}
}