logo

Java에서 파일을 한 줄씩 읽는 방법

파일을 한 줄씩 읽는 방법은 다음과 같습니다.

  • BufferedReader 클래스
  • 스캐너 클래스

BufferedReader 클래스 사용

Java BufferedRedaer 클래스를 사용하는 것은 Java에서 파일을 한 줄씩 읽는 가장 일반적이고 간단한 방법입니다. 에 속한다 java.io 패키지. Java BufferedReader 클래스는 파일을 한 줄씩 읽을 수 있는 readLine() 메서드를 제공합니다. 메소드의 서명은 다음과 같습니다.

 public String readLine() throws IOException 

이 메서드는 텍스트 한 줄을 읽습니다. 행의 내용을 포함하는 문자열을 반환합니다. 줄은 줄 바꿈(' ') 또는 캐리지 리턴(' ') 중 하나로 종료되어야 합니다.

BufferedReader 클래스를 사용하여 파일을 한 줄씩 읽는 예

다음 예에서는 FileReader 클래스에서 Demo.txt를 읽습니다. BufferedReader 클래스의 readLine() 메서드는 파일을 한 줄씩 읽으며, 각 줄은 StringBuffer에 추가되고 그 뒤에 라인 피드가 추가됩니다. 그런 다음 StringBuffer의 내용이 콘솔에 출력됩니다.

 import java.io.*; public class ReadLineByLineExample1 { public static void main(String args[]) { try { File file=new File('Demo.txt'); //creates a new file instance FileReader fr=new FileReader(file); //reads the file BufferedReader br=new BufferedReader(fr); //creates a buffering character input stream StringBuffer sb=new StringBuffer(); //constructs a string buffer with no characters String line; while((line=br.readLine())!=null) { sb.append(line); //appends line to string buffer sb.append('
'); //line feed } fr.close(); //closes the stream and release the resources System.out.println('Contents of File: '); System.out.println(sb.toString()); //returns a string that textually represents the object } catch(IOException e) { e.printStackTrace(); } } } 

산출:

Java에서 파일을 한 줄씩 읽는 방법

Scanner 클래스 사용

자바 스캐너 클래스는 BufferedReader 클래스에 비해 더 많은 유틸리티 메서드를 제공합니다. Java Scanner 클래스는 파일 내용의 한 줄씩 쉽게 처리할 수 있도록 nextLine() 메서드를 제공합니다. nextLine() 메서드는 readLine() 메서드와 동일한 문자열을 반환합니다. Scanner 클래스는 InputStream 형식의 파일을 읽을 수도 있습니다.

Scanner 클래스를 사용하여 파일을 한 줄씩 읽는 예

 import java.io.*; import java.util.Scanner; public class ReadLineByLineExample2 { public static void main(String args[]) { try { //the file to be opened for reading FileInputStream fis=new FileInputStream('Demo.txt'); Scanner sc=new Scanner(fis); //file to be scanned //returns true if there is another line to read while(sc.hasNextLine()) { System.out.println(sc.nextLine()); //returns the line that was skipped } sc.close(); //closes the scanner } catch(IOException e) { e.printStackTrace(); } } } 

산출:

Java에서 파일을 한 줄씩 읽는 방법