Text files: write and read with Scanner · 文本文件:用 Scanner 写和读
Reading and writing text files
- A text file stores text that stays on disk after the program ends.
- To read a file in Java we use a
Scannerconnected to aFile. - To write a file we use a
PrintWriter. In this lesson each program writes a file, then reads it back. - Bonus lesson: the AP CSA exam does not test file input/output. Learn this for real programs — you will not be examined on it.
读写文本文件
- 文本文件(text file)把文字存到磁盘上,程序结束后它还在。
- 在 Java 里读文件,我们用一个连到
File的Scanner。 - 写文件我们用
PrintWriter。在这一课里,每个程序先写一个文件,再把它读回来。 - 附加内容: AP CSA 考试不考文件输入输出。学它是为了写真实的程序 —— 考试不会考。
Reading and writing a file · 读写一个文件
A file is used in three steps: open · 开放的 it, read or write lines, then close · 关闭 it. · 用文件分三步:打开它,读或写每一行,然后关闭它。
The imports you need
- File tools live in two places, so we import both at the top.
import java.io.*;— forFile,PrintWriter, andIOException.import java.util.Scanner;— for theScannerreader.
你需要的 import
- 文件工具放在两个地方,所以我们在顶部把两个都导入。
import java.io.*;—— 用于File、PrintWriter和IOException。import java.util.Scanner;—— 用于读取器Scanner。
import java.io.*;
import java.util.Scanner;
Files can fail, so we say throws IOException
- Reading or writing a file can go wrong (the file may be missing).
- Java makes you handle this. The simplest way is to add
throws IOExceptiontomain. - This says "if a file error happens, let the program stop". That is fine for these tasks.
文件可能出错,所以我们写 throws IOException
- 读或写文件可能会出问题(文件可能不存在)。
- Java 要求你处理这种情况。最简单的办法是给
main加上throws IOException。 - 这句话的意思是"如果发生文件错误,就让程序停下来"。对这些任务来说这样就够了。
Writing a file with PrintWriter
new PrintWriter("data.txt")makes (or empties) a file calleddata.txt.- Use
writer.println(...)to write one line, just like printing to the screen. - Always call
writer.close()when you finish, so the text is saved.
用 PrintWriter 写文件
new PrintWriter("data.txt")会创建(或清空)一个叫data.txt的文件。- 用
writer.println(...)写一行,就像往屏幕上打印一样。 - 写完后一定要调用
writer.close(),这样文字才会被保存。
import java.io.*;
public class WriteDemo {
public static void main(String[] args) throws IOException {
PrintWriter writer = new PrintWriter("data.txt");
writer.println(10);
writer.println(20);
writer.close(); // save the file
System.out.println("wrote data.txt");
}
}
Reading numbers with Scanner
new Scanner(new File("data.txt"))opens the file for reading.in.hasNextInt()istruewhile there is another whole number to read.in.nextInt()reads the next whole number. Callin.close()when done.
用 Scanner 读数字
new Scanner(new File("data.txt"))打开文件来读取。- 只要还有下一个整数,
in.hasNextInt()就是true。 in.nextInt()读取下一个整数。读完后调用in.close()。
import java.io.*;
import java.util.Scanner;
public class ReadNumbers {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("data.txt"));
int total = 0;
while (in.hasNextInt()) { // more numbers?
total = total + in.nextInt();
}
in.close();
System.out.println(total);
}
}
Reading whole lines
- Sometimes a line is text, not a number. Then read lines instead.
in.hasNextLine()istruewhile there is another line.in.nextLine()reads the whole next line as aString.
整行读取
- 有时一行是文字,而不是数字。那就改成读整行。
- 只要还有下一行,
in.hasNextLine()就是true。 in.nextLine()把下一整行作为一个String读进来。
hasNext()(noIntorLine) checks for the next word, andnext()reads one word.- The pattern is always: check with a
hasNext...method, then read with the matching method.
import java.io.*;
import java.util.Scanner;
public class ReadLines {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("data.txt"));
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println("read: " + line);
}
in.close();
}
}
hasNext()(后面没有Int或Line)检查下一个单词,next()读取一个单词。- 套路始终是:先用
hasNext...方法检查,再用对应的方法读取。
Write then read in one program
- In each task your program first writes a file, then reads the same file back.
- This means you can run it again and again and get the same result.
在一个程序里先写后读
- 在每个任务里,你的程序先写一个文件,然后把同一个文件读回来。
- 这样你可以一遍又一遍地运行它,得到相同的结果。
import java.io.*;
import java.util.Scanner;
public class RoundTrip {
public static void main(String[] args) throws IOException {
PrintWriter writer = new PrintWriter("data.txt");
writer.println(3);
writer.println(4);
writer.close();
Scanner in = new Scanner(new File("data.txt"));
int total = 0;
while (in.hasNextInt()) {
total = total + in.nextInt();
}
in.close();
System.out.println(total); // 7
}
}
Common mistakes
nextInt()leaves the newline, so a followingnextLine()reads an empty line.- Check
hasNext()before reading to avoid running off the end.
常见错误
nextInt()会留下换行符,导致紧接的nextLine()读到空行。- 读之前检查
hasNext(),避免读过末尾。
Now you try
- Each task pre-fills a class. Write the file first, then read it back, as the prompt asks.
- Remember the
throws IOExceptiononmain, andclose()both the writer and theScanner. - Press Run to compile and run, then Check answer.
现在轮到你
- 每个任务都预填好了一个类。按提示要求,先写文件,再把它读回来。
- 记得给
main加上throws IOException,并且把 writer 和Scanner都close()。 - 按运行来编译并运行,然后按检查答案。
First write the numbers 10, 20, 5, 7 to · 到 data.txt (one per line) with a PrintWriter. Then open it with new Scanner(new File("data.txt")) and use hasNextInt/nextInt to add them up. Print only the total. Expected output: 42. · 先用 PrintWriter 把数字 10、20、5、7 写到 data.txt(每行一个)。然后用 new Scanner(new File("data.txt")) 打开它,用 hasNextInt/nextInt 把它们加起来。只打印总和。期望输出:42。
Click Run to see the output here. · 点击“运行”查看此处输出。
First write the lines apple, banana, cherry to · 到 words.txt with a PrintWriter. Then open it with a Scanner and use hasNextLine/nextLine to count the lines. Print only the count. Expected output: 3. · 先用 PrintWriter 把 apple、banana、cherry 三行写到 words.txt。然后用 Scanner 打开它,用 hasNextLine/nextLine 数出有多少行。只打印行数。期望输出:3。
Click Run to see the output here. · 点击“运行”查看此处输出。