EOF
EOF(End of File)는 읽고 있는 파일의 끝에 도달했을 때의 상태를 의미한다.
App에 따라 데이터 처리, 파일 검증 등의 작업이 필요할 수 있기 때문에 File을 읽을 때 EOF 감지는 필수다.
아래 사이트에서 Java에서 EOF를 감지하는 여러 방법을 소개하고 있는데
그중 Scanner와 BufferedReader에 대해 정리할 것이다.
https://www.baeldung.com/java-file-detect-end-of-file
Scanner
Scanner는 java.util 패키지의 클래스로 EOF를 감지 및 대처할 수 있는 hasNext() 메서드를 제공한다.
EOF 상태면 false를 반환하기에 아래와 같이 활용할 수 있다.
String readWithScanner() throws IOException {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String line = scanner.nextLine();
System.out.println(line);
}
}
Scanner는 다양한 유형의 데이터를 쉽게 읽을 수 있지만 BufferedReader보다 느리다.
BufferedReader
알고리즘 문제를 풀 때 코드의 성능을 직관적으로 판단할 수 있는 척도는 소요시간이며 I/O는 이에 큰 영향을 미친다.
따라서 거의 모든 사람들은 Scanner가 아닌 BufferedReader를 사용한다.
하지만 BufferedReader는 EOF를 처리할 수 있는 메서드를 제공하지 않는다.
따라서 아래와 같이 활용해야 한다.
String readWithBufferedReader() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
참고
https://stackoverflow.com/questions/13927326/reading-input-till-eof-in-java
reading input till EOF in java
In C++ if I wish to read input till the EOF I can do it in the following manner while(scanf("%d",&n)) { A[i]=n; i++; } I can then run this code as ./a.out < input.txt. What is the ...
stackoverflow.com
'Java > Java' 카테고리의 다른 글
Java - Short Circuit (0) | 2023.12.04 |
---|---|
Java - 배열 복사와 반복, clone()과 arraycopy() 속도 비교 (0) | 2023.11.21 |
Java - Formatter (1) | 2023.10.23 |
Java - Google Java Style Guide 정리 (3) | 2023.10.10 |
Java - .of .asList .emptyList (0) | 2023.10.02 |