在Java(以及大部分其它类似的语言)中读/写文件会遵循三个步骤:
1)打开文件。将创建名为读取/写入器的对象,该对象使程序具有访问数据的能力。对于读取文本文件,首先要调用FileReader类的构造器,传文件名字。
2)读取/写入文件。打开文件后,就可以用FileReader对象上适当的方法来读取数据。文件既可以逐个字符读取,也可以逐行读取,当然需要更复杂的读取器类来操作。
3)关闭文件。完成数据操作时,用读取器的close方法断开读取器与文件之间的关联。
打开文件时会有异常(IO异常)发生,因为你不知道要打开的文件是否存在,或者说你的文件名字错误。这样就需要我们对这种异常(IOException)try-catch处理,后面的代码会提到。
Java读文本文件需要构造的类为BufferedReader (增强操作数据能力),FileReader,创建读对象的格式为
BufferedReader rd = new BufferedReader(new FileReader("文本文件名字.txt"));
写文件和读文件类似,需要构造BufferedWriter和FileWriter,但是最后需要一个PrintWriter,若目标文件不存在,则会创建目标文件,创建写对象的格式为
PrintWriter wr = new PrintWriter(new BufferedWriter(new FileWriter(
"文本文件名字.txt")));
上述的类都在java.io类库里,所以需要程序导入
import java.io.*;
我们先来看一个简单的例子,逐个字符地读取文件。我们使用了read方法,在while循环里我们不断调用它,使得读取器对象不断后移返回新的字符给ch。文件结尾的字符是EOF(-1)所以我们以此为判断条件跳出循环。另外,我们暂时不需关注异常处理的细节,我们只需按照这个框架来组织程序即可。
import java.io.*;
public class Test {
public static void main(String[] args){
try {
BufferedReader rd = new BufferedReader(new FileReader("Hello.txt"));
while (true) {
int ch = rd.read();
if (ch == -1) break;
System.out.print((char) ch);
}
rd.close();
} catch(IOException ex) {
throw new RuntimeException(ex.toString());
}
}
}
按列读取类似,只不过对应的while循环里改为
String line = rd.readLine();
if (line == null) break;
System.out.println(line);
写文件可以照葫芦画瓢,其中println方法用于写入一整行,printf方法可格式化控制写入字符串,这和System.out.xxx类似:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class WriterTest {
public void run() {
try {
PrintWriter wr = new PrintWriter(new BufferedWriter(new FileWriter("D:\\Hello.txt")));
wr.printf("hello, \t\t\\world您好\n");
wr.close();
} catch (IOException ex) {
throw new RuntimeException(ex.toString());
}
}
public static void main(String[] args) {
new WriterTest().run();
}
}
最后,以一个文本文件拷贝程序结束本次的学习:
import java.io.*;
import java.util.Scanner;
public class CopyTxtContentTest {
public static void run() {
try{
Scanner sysin = new Scanner(System.in);
System.out.print("Input the filename you want to copy: ");
String copy = sysin.nextLine();
System.out.print("Input the filename you copy to: ");
String copyto = sysin.nextLine();
BufferedReader rd = new BufferedReader(new FileReader(copy));
PrintWriter wd = new PrintWriter(new BufferedWriter(new FileWriter(copyto)));
while (true) {
String line = rd.readLine();
if (line == null) break;
wd.println(line);
}
rd.close();
wd.close();
} catch (IOException ex) {
throw new RuntimeException(ex.toString());
}
}
public static void main(String[] args) {
run();
}
}