[java] 자바 파일 시스템에서 파일 읽고 쓰기

자바 프로그램에서 파일 시스템으로 파일을 읽고 쓰는 것은 매우 일반적입니다. 이 기능을 수행하는 방법에 대해 알아보겠습니다.

파일 읽기

자바에서 파일을 읽기 위해서는 FileFileInputStream 클래스를 사용합니다. 다음은 간단한 예제입니다.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileReadingExample {
    public static void main(String[] args) {
        File file = new File("파일경로/파일이름.txt");
        try (FileInputStream fis = new FileInputStream(file)) {
            int content;
            while ((content = fis.read()) != -1) {
                System.out.print((char) content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제에서는 FileInputStream을 사용하여 파일에서 데이터를 읽어오고 있습니다. read() 메서드를 사용하여 파일에서 한 바이트씩 읽어오며, 데이터의 끝에 도달하면 -1을 반환합니다.

파일 쓰기

파일에 데이터를 쓰려면 FileOutputStream 클래스를 사용합니다. 다음은 파일에 데이터를 쓰는 예제입니다.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileWritingExample {
    public static void main(String[] args) {
        String content = "파일에 쓸 내용";
        File file = new File("파일경로/파일이름.txt");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            byte[] bytes = content.getBytes();
            fos.write(bytes);
            System.out.println("파일에 쓰기 완료");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제에서는 FileOutputStream을 사용하여 파일에 데이터를 씁니다. getBytes() 메서드로 문자열을 바이트 배열로 변환한 후 write() 메서드로 파일에 데이터를 씁니다.

결론

이렇게 자바에서 파일을 읽고 쓰는 방법에 대해 간략히 살펴보았습니다. 파일 시스템을 다루는 것은 자바 프로그래밍의 중요한 부분이며, 파일을 다룰 때는 예외 처리를 잊지 말아야 합니다.

참고 자료