⭐ [Java] File, Files, Path 파일 클래스 생성/write/read 하기

devdo·2022년 9월 7일

Java

목록 보기
51/61
post-thumbnail

텍스트 파일에 있는 내용을 읽어 오는 기능(read)과
원하는 내용의 텍스트 파일을 윈도우의 원하는 경로에 쓰는(write) 자바 예제입니다.

✅ 자바의 파일 다루기 라이브러리 크게 전통적 방식과 현대적 방식으로 나뉘어집니다.

Java File 라이브러리

해당 기능을 구현하기 위해 Java에서 기본으로 제공해 주는

현대 방식

  • File

전통적 방식

  • BufferedReader/Wrtier
  • FileReader/Writer

클래스를 사용했고,

예외 처리를 위해 try ~ catch, finally 문도 꼭 사용 하게 됩니다.

read / write의 대상은 다양합니다. 아래 예제처럼 텍스트나 파일일 될 수도 있고, 음성이나 영상이 될 수도 있으며, 웹 페이지(웹 크롤링 #1, #2) 가 될 수도 있습니다. (그리고 시대가 계속 흐름에 따라 그 read / write 대상의 사이즈가 점점 커지면서 빅데이터라는 개념이 생긴 거겠죠)

⭐ 전통적 방식 vs 현대 방식

구분BufferedReader (전통 방식)Files.lines() (Java 8+ 방식)
핵심 기술java.io (Blocking IO)java.nio.file (New IO 2)
처리 방식명령형(Imperative) 방식
while 문을 이용한 순차 처리
선언형(Declarative) 방식
→ Stream API 기반 함수형 처리
속도매우 빠름
(기본 8KB 버퍼링 사용)
매우 빠름
(내부적으로 BufferedReader 사용)
가독성다소 복잡함
(try-finally, close() 명시 필요)
매우 간결함
(코드 라인 수 적고 가독성 우수)
병렬 처리구현 난이도 높음
(직접 병렬 로직 작성 필요)
매우 쉬움
(.parallel() 호출로 즉시 가능)
메모리 사용한 줄씩 읽음
→ 메모리 효율적
한 줄씩 읽음 (Lazy Loading)
→ 메모리 효율적

java example

✅ 업데이트 버전 2025.12

        // java File 다루기
        // 쓰기 겨올 ./test/example.txt
        // OS에 맞는 줄바꿈 문자를 가져옴
        String newline = System.lineSeparator(); // ⭐ windwows: \r\n , Linux: \n

        Path path = Paths.get("test", "example.txt");
        System.out.println("Absolute Path: " + path.toAbsolutePath());
        System.out.println("File Name: " + path.getFileName());

        List<String> content = List.of("안녕하세요", "Datamatica STEP 백엔드 애플리케이션입니다.");

        try {
            Files.write(path, content);

            String appendText = newline + "파일에 새로운 줄을 추가합니다.";

            Files.writeString(path, appendText, java.nio.file.StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 읽기, 🎯 주의! 읽을 때 한글이 포함된 파일이라면 StandardCharsets.UTF_8을 명시! (OS 기본 설정에 따라 깨질 수 있음)
        if(Files.exists(path)) {
            System.out.println("--- 파일 읽기 시작 ---");
            try {
                System.out.println("일반 파일 읽기 - File Size: " + Files.size(path) + " bytes");
                List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
                System.out.println("File Content:");
                for (String line : lines) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();

            }

            // 대용량 읽기 Stream 사용
            System.out.println("--- Stream을 이용한 파일 읽기 ---");
            try (Stream<String> linesStream = Files.lines(path, StandardCharsets.UTF_8)) {
                linesStream.forEach(System.out::println);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

읽기 성능 테스트

            // 일반 읽기
            long start1 = System.nanoTime();
            try {
                System.out.println("일반 파일 읽기 - File Size: " + Files.size(path) + " bytes");
                List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
                System.out.println("File Content:");
                for (String line : lines) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            long end1 = System.nanoTime();
            System.out.printf("저용량 방식 소요 시간: %d ns (약 %.3f ms)%n",
                    (end1 - start1), (end1 - start1) / 1_000_000.0);

            // 대용량 읽기 Stream 사용
            System.out.println("--- Stream을 이용한 파일 읽기 ---");
            long start2 = System.nanoTime();
            try (Stream<String> linesStream = Files.lines(path, StandardCharsets.UTF_8)) {
                linesStream.forEach(System.out::println);
            } catch (IOException e) {
                e.printStackTrace();
            }
            long end2 = System.nanoTime();
            System.out.printf("대용량 방식 소요 시간: %d ns (약 %.3f ms)%n",
                    (end2 - start2), (end2 - start2) / 1_000_000.0);

✳️ 대용량 Stream 파일 읽기가 확실히 2배 정도 성능이 좋다.


  • 전통방식(BufferedReader, BufferedWriter )
public class FileText {

    public String read(String path, String fileName) {

        File file = new File(path, fileName);
        BufferedReader br;
        String retStr = "";

        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("line: " + line);
                retStr += line + "\n";
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return retStr;
    }

    public void write(String path, String fileName, String content) {
        File file = new File(path, fileName);

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

  • Main 클래스
public class Main {

    public static void main(String[] args) {

        // Writer
        String path = "C:\\test";
        String fileName = "test.txt";
        FileText ft = new FileText();
        ft.write(path, fileName, "저를 소개합니다. 도성곤입니다. \n감사합니다!! ");

        // Reader
        String result = ft.read(path, fileName);
        System.out.println(result);
    }
}

Files, Path

Files와 Path 클래스는 jdk1.7 버전때 나온 클래스입니다. Java NIO (New Input/Output) 패키지에서 제공하는 클래스로, 파일 및 디렉토리 작업을 간편하게 처리할 수 있게 도와줍니다. 기존의 File 클래스보다 더 많은 기능을 가지고 있습니다.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class FileOperationsExample {

    public static void main(String[] args) throws IOException {
        // 파일 읽기 예제
        readFileExample();

        // 파일 쓰기 예제
        writeFileExample();

        // 파일 복사 예제
        copyFileExample();

        // 파일 삭제 예제
        deleteFileExample();

        // Path 클래스 예제
        pathExample();
        
        // Path 정보 가져오기 예제
        pathInfoExample();
        
        // 절대 경로로 변환 예제
        absolutePathExample();
    }

    // 파일 읽기 메서드
    private static void readFileExample() throws IOException {
        Path path = Paths.get("example.txt");
        List<String> lines = Files.readAllLines(path);
        System.out.println("Reading File:");
        for (String line : lines) {
            System.out.println(line);
        }
        System.out.println();
    }

    // 파일 쓰기 메서드
    private static void writeFileExample() throws IOException {
        Path path = Paths.get("example.txt");
        List<String> lines = List.of("Hello", "World");
        Files.write(path, lines);
        System.out.println("File written successfully!\n");
    }

    // 파일 복사 메서드
    private static void copyFileExample() throws IOException {
        Path source = Paths.get("source.txt");
        Path target = Paths.get("target.txt");
        Files.copy(source, target);
        System.out.println("File copied successfully!\n");
    }

    // 파일 삭제 메서드
    private static void deleteFileExample() throws IOException {
        Path path = Paths.get("example.txt");
        Files.delete(path);
        System.out.println("File deleted successfully!\n");
    }

    // Path 클래스 예제 메서드
    private static void pathExample() {
        Path path = Paths.get("example.txt");
        System.out.println("Path: " + path + "\n");
    }

    // Path 정보 가져오기 메서드
    private static void pathInfoExample() {
        Path path = Paths.get("example.txt");
        System.out.println("File Name: " + path.getFileName());
        System.out.println("Parent Directory: " + path.getParent());
        System.out.println("Root: " + path.getRoot() + "\n");
    }

    // 절대 경로로 변환 메서드
    private static void absolutePathExample() {
        Path path = Paths.get("example.txt");
        Path absolutePath = path.toAbsolutePath();
        System.out.println("Absolute Path: " + absolutePath + "\n");
    }
}


출처

profile
배운 것을 기록합니다.

0개의 댓글