Java 使用FileWriter和FileReader处理文件
Java的FileWriter和FileReader类是用来写和读文本文件的数据的(它们是字符流类)。如果你要读写任何文本信息,建议 不要 使用FileInputStream和FileOutputStream类,因为这些是字节流类。
FileWriter
FileWriter对于创建一个文件并向其中写入字符是很有用的。
- 这个类继承于OutputStream类。
- 这个类的构造函数假定默认的字符编码和默认的字节缓冲区大小是可以接受的。要想自己指定这些值,请在一个FileOutputStream上构造一个OutputStreamWriter。
-
FileWriter是用来写字符流的。如果要写原始字节流,可以考虑使用FileOutputStream。
- 如果输出文件不存在,FileWriter会创建它。
构造函数
- FileWriter(File file) – 构建一个 FileWriter 对象,给定一个 File 对象。
- FileWriter ( File file, boolean append) – 构建一个 FileWriter 对象,给定一个 File 对象。
- FileWriter (FileDescriptor fd) – 构造一个与文件描述符相关的 FileWriter 对象。
- FileWriter (String fileName) – 根据文件名构造一个 FileWriter 对象。
- FileWriter (String fileName, Boolean append) – 构造一个FileWriter对象,给定一个文件名,用一个布尔值表示是否要附加所写的数据。
方法
- public void write (int c) throws IOException – 写一个字符。
- public void write ( char [] stir) throws IOException – 写一个字符阵列。
- public void write(String str)throws IOException – 写一个字符串。
- public void write(String str, int off, int len)throws IOException – 写一个字符串的一部分。这里off是开始写入字符的偏移量,len是要写入的字符数。
- public void flush() throws IOException 冲洗流。
- public void close() throws IOException 首先冲刷流,然后关闭写入器。
读和写都是逐个字符进行的,这增加了I/O操作的数量,影响了系统的性能。 BufferedWriter 可以和FileWriter一起使用,以提高执行速度。
以下程序描述了如何使用FileWriter创建一个文本文件
文件读取器
FileReader对于从 “文本 “文件中读取字符形式的数据非常有用。
- 这个类继承于InputStreamReader类。
- 这个类的构造函数假定默认的字符编码和默认的字节缓冲区大小是合适的。要自己指定这些值,请在FileInputStream上构造一个InputStreamReader。
-
FileReader是用来读取字符流的。对于读取原始字节流,可以考虑使用 FileInputStream。
构造函数
- FileReader(File file) – 创建一个FileReader,给定要读取的文件。
- FileReader(FileDescripter fd) – 创建一个新的FileReader,给定要读取的FileDescripter。
- FileReader(String fileName) – 创建一个新的FileReader,给定要读取的文件名。
方法
- public int read () throws IOException – 读取单个字符。该方法将阻塞,直到有一个可用的字符,发生I/O错误,或者到达流的末端。
-
public int read(char[] cbuff) throws IOException – 读取字符到一个数组。该方法将阻塞,直到有可用的输入,发生I/O错误,或者到达流的末端。
-
public abstract int read(char[] buff, int off, int len) throws IOException – 将字符读入一个数组的一部分。该方法将阻塞,直到有一些输入,发生I/O错误,或者到达流的末端。
参数:
cbuf – 目标缓冲区
off – 开始存储字符的偏移量
len – 要读取的最大字符数
-
public void close() throws IOException 关闭阅读器。
-
public long skip(long n) throws IOException – 跳过字符。该方法将阻塞,直到有一些字符可用,发生I/O错误,或者到达流的末端。
参数:
n – 要跳过的字符数
下面的程序描述了如何使用FileReader从 “text “文件中读取