FileReader & FileWriter : 文件字符流 操作的是字符
//FileReader 文件字符输入流
//1、创建源
File src = new File("abc.txt");
//2、选择流
Reader reader =null;
try {
reader =new FileReader(src);
//3、操作 (分段读取)
char[] flush = new char[1024]; //缓冲容器
int len = -1; //接收长度
while((len=reader.read(flush))!=-1) {
//字符数组-->字符串
String str = new String(flush,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//4、释放资源
try {
if(null!=reader) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//FileWriter 文件字符输出流
//1、创建源
File dest = new File("dest.txt");
//2、选择流
Writer writer =null;
try {
writer = new FileWriter(dest);
//3、操作(写出)
//写法一 先写入字符数组
// String msg ="IO is so easy\r\n";
// char[] datas =msg.toCharArray(); // 字符串-->字符数组
// writer.write(datas,0,datas.length);
//写法二 直接传入字符串
/*String msg ="IO is so easy\r\n";
writer.write(msg);
writer.write("add");
writer.flush();*/
//写法三 调用append()方法
writer.append("IO is so easy\r\n").append("哈哈");
writer.flush();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
//4、释放资源
try {
if (null != writer) {
writer.close();
}
} catch (Exception e) {
}
}