← Java 처음부터
레슨 58 / 88 · 10 XP
파일 읽기
이론과 문제
기계 번역이에요. 아직 원어민이 검토하지 않았어요.
import java.io.File;
import java.util.Scanner;
try (Scanner sc = new Scanner(new File("scores.txt"))) { // FileNotFoundException — 검사 예외
while (sc.hasNextLine()) {
String line = sc.nextLine();
…
}
}
Files로는:
String all = Files.readString(Path.of("a.txt"));
List<String> lines = Files.readAllLines(Path.of("a.txt"));
try (Stream<String> s = Files.lines(Path.of("big.txt"))) { … } // 게으르게 — 큰 파일에
전부 메모리로 읽기(readAllLines)는 작은 파일에; 큰 파일은 줄 단위로 읽어요.
과제. 프로그램이 입력의 name score 줄을 이미 scores.txt에 썼어요. 파일을 읽고
(Scanner(new File(...))로) 최고 플레이어를 name (score)로, 점수 합계, 플레이어 수를 출력하세요.