[java] Apache Commons IO를 이용한 텍스트 파일 처리하기

Apache Commons IO는 자바 언어로 텍스트 파일을 처리하는 데 유용한 도구들을 제공하는 라이브러리입니다. 이 블로그 포스트에서는 Apache Commons IO를 사용하여 텍스트 파일을 읽고 쓰는 방법을 살펴보겠습니다.

Apache Commons IO 라이브러리 추가하기

먼저, Apache Commons IO 라이브러리를 프로젝트에 추가해야 합니다. Maven을 사용하는 경우, pom.xml 파일에 다음 의존성을 추가하십시오:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.1</version>
</dependency>

Gradle을 사용하는 경우, build.gradle 파일의 dependencies 블록에 다음 라인을 추가하십시오:

implementation 'commons-io:commons-io:2.11.1'

이제 Apache Commons IO를 사용할 준비가 되었습니다.

텍스트 파일 읽기

Apache Commons IO를 사용하여 텍스트 파일을 읽을 때에는 FileUtils 클래스의 readFileToString 메서드를 사용합니다. 다음은 텍스트 파일을 읽는 예제 코드입니다:

import org.apache.commons.io.FileUtils;

public class TextFileReader {
    public static void main(String[] args) {
        String filePath = "path/to/textfile.txt";
        
        try {
            String content = FileUtils.readFileToString(new File(filePath), "UTF-8");
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 코드는 FileUtils.readFileToString 메서드를 사용하여 지정된 경로의 텍스트 파일을 읽고, 문자열로 반환한 후, 해당 문자열을 콘솔에 출력합니다. 필요에 따라 읽은 내용을 다른 방식으로 활용할 수 있습니다.

텍스트 파일 쓰기

Apache Commons IO를 사용하여 텍스트 파일을 쓸 때에는 FileUtils 클래스의 writeStringToFile 메서드를 사용합니다. 다음은 텍스트 파일을 쓰는 예제 코드입니다:

import org.apache.commons.io.FileUtils;

public class TextFileWriter {
    public static void main(String[] args) {
        String filePath = "path/to/textfile.txt";
        String content = "Hello, world!";
        
        try {
            FileUtils.writeStringToFile(new File(filePath), content, "UTF-8");
            System.out.println("Text file written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 코드는 FileUtils.writeStringToFile 메서드를 사용하여 지정된 경로에 문자열을 포함한 텍스트 파일을 생성합니다. 생성이 성공하면 성공 메시지를 콘솔에 출력합니다.

요약

Apache Commons IO를 사용하면 간단하고 효율적으로 텍스트 파일을 처리할 수 있습니다. FileUtils 클래스의 readFileToString 메서드로 텍스트 파일을 읽고, writeStringToFile 메서드로 텍스트 파일을 생성할 수 있습니다. 추가적인 기능과 메서드에 대해서는 Apache Commons IO 공식 문서를 참조하십시오.