之前提到了字节流,字节流中没有编码的概念,不能按行处理,使用不太方便。
字符流有一个PrintWriter 在我们做标准输出的很好用,非常方便,可以指定指定文件名字作为参数,可以指定编码类型,自动缓冲,在我们输出文件时,可以优先选择该类。
public PrintWriter(File file) throws FileNotFoundException
public PrintWriter(File file, String csn)
public PrintWriter(String fileName, String csn)
public PrintWriter(OutputStream out)
public PrintWriter (Writer out)
public PrintWriter(Writer out, boolean autoFlush)
public PrintWriter(OutputStream out, boolean autoFlush) {
this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);
...
}
public PrintWriter(String fileName) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
}
总结:
写文件时,可以优先考虑PrintWriter,因为它使用方便,支持自动缓冲、支持指定编码类型、支持类型转换等。
PrintWriter writer=new PrintWriter("C:\\Users\\zhanght\\Desktop\\out.txt","UTF-8");
读文件时,如果需要指定编码类型,需要使用InputStreamReader,不需要,可使用FileReader,但都应该考虑在外面包上缓冲类BufferedReader。
Reader reader=new BufferedReader(new InputStreamReader(new FileInputStream("path"),"UTF-8"))
Reader reader1=new BufferedReader(new FileReader("path"));