------- android培训、java培训、期待与您交流! ----------
import java.io.*;
class IoDemo {
public static void main(String[] args) {
FileWriter fw = null;
FileReader fr = null;
try {
fw = new FileWriter("c:\\test.txt");
fr = new FileReader("IoDemo.java");
char[] ch = new char[1024];
int length = 0;
while ((length = fr.read(ch)) != -1) {
fw.write(ch, 0, length);
}
} catch (Exception e) {
System.out.println("读取数据错误");
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
System.out.println(e);
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
}
这是用字符数组对文件进行读写操作。下面是用字符对文件进行读写操作的示例:
import java.io.*;
class IoDemo2 {
public static void main(String[] args) throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("IoDemo2.java");
fw = new FileWriter("test2.txt");
int ch;
while ((ch = fr.read()) != -1) {
fw.write(ch);
fw.flush();
}
} catch (IOException e) {
} finally {
if (fr != null) {
fr.close();
}
if (fw != null) {
fw.close();
}
}
}
}
编译通过,并运行成功。
本文详细介绍了Java中的IO(input/output)输入输出概念,包括字节和字符的存取方法,通过实例展示了使用FileWriter和FileReader类进行文件读写操作的过程。

1870

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



