[java] Apache Commons IO를 이용한 파일 읽기 및 쓰기 동시 처리하기

이번 포스트에서는 Java에서 Apache Commons IO 라이브러리를 사용하여 파일을 동시에 읽고 쓰는 방법을 알아보겠습니다. Apache Commons IO는 파일 및 디렉토리 조작을 쉽게할 수 있도록 도와주는 유용한 라이브러리입니다.

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

먼저, 프로젝트에 Apache Commons IO 라이브러리를 추가해야 합니다. Maven을 사용한다면, pom.xml 파일에 다음 의존성을 추가합니다.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

Gradle을 사용한다면, build.gradle 파일에 다음 의존성을 추가합니다.

implementation 'commons-io:commons-io:2.8.0'

2. 파일 읽기 및 쓰기

2.1. 파일 읽기

import org.apache.commons.io.FileUtils;

public class FileReadExample {
    public static void main(String[] args) {
        try {
            // 파일 읽기
            String fileContent = FileUtils.readFileToString(new File("input.txt"), "UTF-8");
            
            // 읽은 파일 내용 출력
            System.out.println(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제는 input.txt 파일의 내용을 읽어와서 변수 fileContent에 저장하고, 그 값을 출력하는 간단한 예제입니다. 파일을 읽을 때는 FileUtils.readFileToString() 메서드를 사용하면 됩니다.

2.2. 파일 쓰기

import org.apache.commons.io.FileUtils;

public class FileWriteExample {
    public static void main(String[] args) {
        try {
            // 파일 쓰기
            String fileContent = "Hello, world!";
            FileUtils.writeStringToFile(new File("output.txt"), fileContent, "UTF-8");
            
            System.out.println("파일이 성공적으로 쓰여졌습니다.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제는 변수 fileContent의 값을 output.txt 파일에 쓰는 간단한 예제입니다. 파일을 쓸 때는 FileUtils.writeStringToFile() 메서드를 사용하면 됩니다.

3. 파일 읽기 및 쓰기 동시 처리

import org.apache.commons.io.FileUtils;

public class FileReadWriteExample {
    public static void main(String[] args) {
        try {
            // 파일 읽기
            String fileContent = FileUtils.readFileToString(new File("input.txt"), "UTF-8");
            
            // 읽은 파일 내용을 가공하여 변수에 저장
            String processedContent = processFileContent(fileContent);
            
            // 파일 쓰기
            FileUtils.writeStringToFile(new File("output.txt"), processedContent, "UTF-8");
            
            System.out.println("파일 읽기와 쓰기가 동시에 처리되었습니다.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static String processFileContent(String content) {
        // 파일 내용 가공 처리 로직
        return content.toUpperCase();
    }
}

위의 예제는 파일을 동시에 읽고 쓰는 방법을 보여주는 예제입니다. FileReadWriteExample 클래스에서 파일을 읽어와서 가공한 후, 다시 파일에 쓰고, 해당 내용을 출력합니다.

Apache Commons IO 라이브러리를 사용하면, 파일을 읽고 쓰는 작업을 간편하게 처리할 수 있습니다. 파일 조작에 대한 다양한 기능들을 제공하므로, 더욱 효율적인 파일 처리 작업이 가능해집니다.

더 자세한 내용은 Apache Commons IO 공식 문서를 참고하세요.