Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 파일 내용을 문자열로 읽어오는 방법

Java에서 파일의 내용을 읽는 방법은 여러 가지가 있으며, 그중 하나는 java.util.Scanner 클래스를 사용해 파일 내용을 하나의 문자열(String)로 읽어오는 방식입니다. 절차는 다음과 같습니다.

  • 읽을 파일의 경로를 생성자 매개변수로 전달하여 Scanner 클래스의 객체를 생성합니다.

  • 내용을 담을 빈 StringBuffer 객체를 만듭니다.

  • hasNextLine() 메서드를 조건으로 하는 while 루프를 시작합니다.

  • 루프 안에서 append() 메서드를 사용해 파일의 각 줄을 StringBuffer 객체에 추가합니다.

  • toString() 메서드를 사용해 버퍼의 내용을 최종적으로 String으로 변환합니다.

예제

먼저 시스템의 C 드라이브에 sample.txt라는 이름의 파일을 생성하고, 아래 내용을 복사해 붙여넣습니다.

Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class 
of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, 
in your own space.

After a successful journey of providing the best learning content at tutorialspoint.com, we created 
our subscription based premium product called Tutorix to provide Simply Easy Learning in the best 
personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.

다음 Java 프로그램은 sample.txt 파일의 내용을 문자열로 읽어 들인 후 화면에 출력합니다.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileToString {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(new File("E://test//sample.txt"));
        String input;
        StringBuffer sb = new StringBuffer();
        while (sc.hasNextLine()) {
            input = sc.nextLine();
            sb.append(" "+input);
        }
        System.out.println("Contents of the file are: "+sb.toString());
    }
}

실행 결과

Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to 
provide knowledge to that class of readers that responds better to online content. With Tutorials Point, 
you can learn at your own pace, in your own space. After a successful journey of providing the best 
learning content at tutorialspoint.com, we created our subscription based premium product called 
Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants 
of competitive exams like IIT/JEE and NEET.

참고: 더 간단한 현대적인 방법

Java 11 이상을 사용한다면 Files.readString() 메서드를 활용하면 위 과정을 한 줄로 처리할 수 있습니다.

import java.nio.file.Files;
import java.nio.file.Path;

String content = Files.readString(Path.of("E://test//sample.txt"));
System.out.println(content);

이 방법은 문자 인코딩(기본값 UTF-8)도 자동으로 처리해 주므로, 최신 Java 환경에서는 더욱 권장되는 방식입니다. 반면 Java 8 이하 버전을 사용하거나 줄 단위 처리 로직이 필요한 경우에는 앞서 소개한 Scanner 방식이 유용합니다.