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.
하나의 프로그램에서 쓰기 및 읽기
- 각 과제에서 프로그램은 먼저 파일을 쓴 후, 같은 파일을 다시 읽습니다.
- 즉, repeatedly 실행해도 동일한 결과를 얻을 수 있습니다.
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 버튼을 눌러 컴파일하고 실행한 후, 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. · 출력을 보려면 '실행'을 클릭하세요.