字符流 文件赋值操作
@Test
public void testFileReaderFileWriter() {
// 不能使用字符流来处理图片等字节数据
FileReader fr = null;
FileWriter fw = null;
try {
// 1. 创建File类的对象 , 指明读入和写出的文件
File srcFile = new File("hello.txt");
File destFile = new File("hello2.txt");
// 2. 创建流的对象:输入流和输出流
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
// 3. 数据的读入和谐出操作
char[] cbuf = new char[5];
int len; // 记录每次读入到cbuf数组中的字符的个数
while ((len = fr.read(cbuf)) != -1) {
// 每次写出len个字符
fw.write(cbuf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4. 关闭流资源
// 方式一:
// try {
// if (fw != null)
// fw.close();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// if (fr != null)
// fr.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// 方式二:
try {
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
本文演示了如何使用Java的FileReader和FileWriter进行字符流文件的读写操作,实现从一个文本文件到另一个文本文件的内容复制。在读取和写入过程中,使用了循环读取字符数组并写出的方法,确保数据完整传输。注意,字符流不适合处理图片等字节数据,且在操作完成后要记得关闭流资源。
2926

被折叠的 条评论
为什么被折叠?



