文件字符流
当使用文件字节流时,由于是读入字节数组,而字节数组大小一定,所以有可能出现乱码。
当操作字符文件时,可使用文件字符流避免产生此问题。
仅适用于操作字符文件。
FileReader
FileReader与FileInputStream区别在于读入到的是字符数组。
File src = new File("Garden.txt");
Reader reader = null;
try {
reader = new FileReader(src);
//注意读入字符数组
char[] flush = new char[1024];
int len;
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 {
try {
if (null!=reader) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter
FileWriter有一个append()方法,和StringBuilder类似。
File dest = new File("dest.text");
Writer writer = null;
try {
writer = new FileWriter(dest,true);
//写法一
//String str = "Makka Pakka 欢迎您";
//char[] flush = str.toCharArray();
//writer.write(flush);
//写法二,可直接丢入字符串
//String str = "Makka Pakka 再欢迎您";
//writer.write(str);
//写法三,使用append()
writer.append("Makka Pakka").append(" 执意还要欢迎您");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (null!=writer) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}