package javaTest01;
import java.io.*;
public class StreamTest02 {
public static void main(String[] args) throws IOException {
File file2=new File("config/streamTest02");
file2.mkdirs();
File file=new File("config/streamTest02/test.txt");
//**************写文件
// 构建FileOutputStream对象,文件不存在会自动新建(但路径必须存在)
FileOutputStream fos=new FileOutputStream(file);
// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
OutputStreamWriter writer=new OutputStreamWriter(fos,"UTF-8");
// 写入到缓冲区
writer.append("烟花三月下扬州");
writer.append("
");
writer.append("where there is a will there is a way");
// 关闭写入流,同时会把缓冲区内容写入文件
writer.close();
fos.close();
//**************读文件
FileInputStream fis=new FileInputStream(file);
InputStreamReader reader=new InputStreamReader(fis,"UTF-8");
StringBuffer sb=new StringBuffer();
while (reader.ready()){
// 转成char加到StringBuffer对象中
sb.append((char) reader.read());
}
System.out.println("sb: " + sb.toString());
reader.close();
fis.close();
}
}