Text files: write and read with Scanner · Tệp văn bản: ghi và đọc với 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.
Đọc và ghi file văn bản
- Một file văn bản lưu trữ văn bản tồn tại trên ổ đĩa sau khi chương trình kết thúc.
- Để đọc một file trong Java, chúng ta sử dụng một
Scannerđược kết nối với mộtFile. - Để ghi một file, chúng ta sử dụng một
PrintWriter. Trong bài học này, mỗi chương trình ghi một file, sau đó đọc lại nó. - Bài học bổ sung: kỳ thi AP CSA không kiểm tra việc nhập/ xuất file. Hãy học điều này cho các chương trình thực tế — bạn sẽ không bị chấm điểm về phần này.
Reading and writing a file · Đọc và ghi tệp
A file is used in three steps: open it, read or write lines, then close it. · Một tệp được sử dụng qua ba bước: mở nó, đọc hoặc ghi các dòng, sau đó đóng nó lại.
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.
Các imports bạn cần
- Các công cụ liên quan đến file nằm ở hai nơi, vì vậy chúng ta import cả hai ở đầu file.
import java.io.*;— choFile,PrintWriter, vàIOException.import java.util.Scanner;— cho trình đọcScanner.
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.
File có thể thất bại, vì vậy chúng ta nói throws IOException
- Việc đọc hoặc ghi file có thể gặp sự cố (file có thể bị thiếu).
- Java yêu cầu bạn xử lý điều này. Cách đơn giản nhất là thêm
throws IOExceptionvàomain. - Điều này có nghĩa là "nếu xảy ra lỗi file, hãy để chương trình dừng lại". Điều đó là ổn cho các nhiệm vụ này.
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.
Ghi một file bằng PrintWriter
new PrintWriter("data.txt")tạo (hoặc làm trống) một file có tên làdata.txt.- Sử dụng
writer.println(...)để ghi một dòng, giống hệt như in lên màn hình. - Luôn gọi
writer.close()khi bạn hoàn tất, để văn bản được lưu lại.
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.
Đọc số bằng Scanner
new Scanner(new File("data.txt"))mở file để đọc.in.hasNextInt()làtruekhi còn một số nguyên khác để đọc.in.nextInt()đọc số nguyên tiếp theo. Gọiin.close()khi đã hoàn tất.
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.
Đọc toàn bộ dòng
- Đôi khi một dòng là văn bản, không phải số. Khi đó hãy đọc dòng thay vì số.
in.hasNextLine()làtruekhi còn một dòng khác.in.nextLine()đọc toàn bộ dòng tiếp theo dưới dạng mộtString.
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()(không cóInthayLine) kiểm tra từ tiếp theo, vànext()đọc một từ.- Mẫu luôn là: kiểm tra bằng một phương thức
hasNext..., sau đó đọc bằng phương thức tương ứng.
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.
Ghi rồi đọc trong một chương trình
- Trong mỗi bài tập, chương trình của bạn trước tiên ghi một file, sau đó đọc lại chính file đó.
- Điều này có nghĩa là bạn có thể chạy nó nhiều lần và nhận được kết quả giống nhau.
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.
Lỗi thường gặp
nextInt()giữ nguyên ký tự xuống dòng, vì vậy mộtnextLine()theo sau sẽ đọc một dòng trống.- Kiểm tra
hasNext()trước khi đọc để tránh vượt quá giới hạn.
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.
Bây giờ bạn thử
- Mỗi bài tập đều có sẵn một class. Hãy viết file trước, sau đó đọc lại, theo yêu cầu của đề bài.
- Nhớ đến
throws IOExceptiontrênmain, vàclose()bao gồm cả người ghi vàScanner. - Nhấn Chạy để biên dịch và chạy, sau đó Kiểm tra câu trả lời.
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. · Đầu tiên viết các số 10, 20, 5, 7 vào file data.txt (mỗi số một dòng) bằng PrintWriter. Sau đó mở file đó bằng new Scanner(new File("data.txt")) và dùng hasNextInt/nextInt để cộng tổng chúng. Chỉ in ra tổng. Kết quả mong đợi: 42.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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. · Đầu tiên viết các đường thẳng apple, banana, cherry đến words.txt với một PrintWriter. Sau đó mở nó ra với một Scanner và sử dụng hasNextLine/nextLine để đếm số đường thẳng. Chỉ in ra kết quả đếm. Kết quả mong đợi: 3.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.