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.
Чтение и запись текстовых файлов
- Текстовый файл хранит текст, который остается на диске после завершения программы.
- Для чтения файла в Java мы используем
Scanner, подключенный кFile. - Для записи файла мы используем
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 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 требует обработки этого. Самый простой способ — добавить
throws IOExceptionкmain. - Это означает «если произойдет ошибка файла, дайте программе остановиться». Для этих задач это приемлемо.
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.
Теперь попробуйте сами
- Каждое задание заранее заполняет класс. Сначала запишите файл, затем прочитайте его обратно, как указано в задании.
- Помните о
throws IOExceptionнаmain, а также оclose()как для писателя, так и дляScanner. - Нажмите Run (Выполнить), чтобы скомпилировать и запустить, затем Check answer (Проверить ответ).
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. · Сначала запишите числа 10, 20, 5, 7 в data.txt (по одному на строку) с помощью PrintWriter. Затем откройте его с помощью 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. · Сначала запишите строки apple, banana, cherry в words.txt с помощью PrintWriter. Затем откройте её с помощью Scanner и используйте hasNextLine/nextLine для подсчета строк. Выведите только количество. Ожидаемый вывод: 3.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.