package com.java;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOTest5 {
/**
* 字符流操作文件读写
*/
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("from.txt");
fw = new FileWriter("to.txt");
// 单个字符的循环输入输出
oneWordIO(fr, fw);
// 一行一行循环输入输出
oneLineIO(fr, fw);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fw.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 一行一行循环输入输出
*/
private static void oneLineIO(FileReader in, FileWriter out)
throws IOException {
char[] buf = new char[1024];
int len = -1;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
out.flush();
}
}
/**
* 单个字符的输入整行输出
*/
private static void oneWordIO(FileReader in, FileWriter out)
throws IOException {
int ch = -1;
while ((ch = in.read()) != -1) {
out.write(ch);
out.flush();
}
}
}
java IO总结之字符流操作文件读写
最新推荐文章于 2024-11-27 14:53:15 发布
本文提供了一个使用Java进行文件读写的示例代码,通过字符流方式实现了从一个文件到另一个文件的数据迁移,包括单个字符及整行数据的读取与写入。
1285

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



