前面介绍了字节流,这里介绍字符流。字符流FileReader可以从文件中读取多字节文本,如:中文。用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的。
实例:读取磁盘目录document下面的reader.txt文件的内容,然后将该文件内容输出到控制台。
package io.reader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileReaderTest { public static void main(String[] args) { FileReader reader = null; try { reader = new FileReader(new File("document/reader.txt")); char[] chars = new char[1024]; int len = -1; // 读取文件内容 while ( (len = reader.read(chars)) != -1 ) { System.out.println( new String(chars, 0, len) ); } } catch (Exception e) { e.printStackTrace(); } finally { if ( null != reader ) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } } }
输出结果:
静夜思 床前明月光,疑是地上霜。 举头望明月,低头思故乡。