0Pricing
Java Academy · 강의

Files 유틸리티: 읽기, 쓰기, 복사, 이동

일반적인 파일 작업에 Files.readString, writeString, copy, move, delete를 사용합니다.

Files 유틸리티: 읽기, 쓰기, 복사, 이동은(는) CoddyKit의 무료 Java Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Java Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

Files 클래스

java.nio.file.Files 클래스는 파일을 읽고, 쓰고, 복사하고, 이동하고, 조회하는 정적 유틸리티 메서드를 제공합니다. 장황한 FileInputStream/FileOutputStream 기본 코드를 대체합니다.

import java.nio.file.*;
import java.io.IOException;

Path file = Path.of("example.txt");
// All Files methods throw IOException — handle or propagate

파일 읽기

파일의 전체 내용을 읽는 최신 메서드입니다:

Path path = Path.of("notes.txt");

// Read as a single String (Java 11+)
String content = Files.readString(path);
System.out.println(content);

// Read as List of lines
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);

// Read as byte array
byte[] bytes = Files.readAllBytes(path);

파일 쓰기

한 번의 호출로 파일에 String 또는 줄 컬렉션을 쓸 수 있습니다:

Path out = Path.of("output.txt");

// Write a String (overwrites by default)
Files.writeString(out, "Hello, NIO.2!");

// Write with StandardOpenOption.APPEND
Files.writeString(out, "\nAppended line", StandardOpenOption.APPEND);

// Write lines
List<String> lines = List.of("line1", "line2", "line3");
Files.write(out, lines);

파일 속성 확인

파일을 열지 않고 파일 메타데이터를 조회할 수 있습니다:

Path path = Path.of("data.txt");

System.out.println(Files.exists(path));       // true/false
System.out.println(Files.isRegularFile(path)); // true if not dir
System.out.println(Files.isDirectory(path));   // true if dir
System.out.println(Files.isReadable(path));    // readable?
System.out.println(Files.size(path));          // bytes
System.out.println(Files.getLastModifiedTime(path));

파일 복사

Files.copy(source, target)는 파일을 복사합니다. 동작을 제어하려면 StandardCopyOption을 사용하세요:

Path src = Path.of("original.txt");
Path dst = Path.of("backup.txt");

// Throws if destination exists (default)
Files.copy(src, dst);

// Overwrite if exists:
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

// Copy preserving file timestamps:
Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES);

파일 이동 및 이름 변경

Files.move()는 파일을 이동하거나 이름을 변경합니다. ATOMIC_MOVE를 사용하면 원자적 이동이 가능합니다:

Path from = Path.of("temp.txt");
Path to   = Path.of("archive/report_2024.txt");

Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);

// Rename in same directory:
Path renamed = from.resolveSibling("new_name.txt");
Files.move(from, renamed, StandardCopyOption.REPLACE_EXISTING);

파일 삭제

삭제 메서드는 두 가지가 있습니다. 하나는 파일을 찾지 못하면 예외를 발생시키고, 다른 하나는 그렇지 않습니다:

Path file = Path.of("temp.txt");

// Throws NoSuchFileException if file doesn't exist:
Files.delete(file);

// Returns false if file didn't exist (no exception):
boolean deleted = Files.deleteIfExists(file);
System.out.println("Deleted: " + deleted);

디렉터리 생성

중간 디렉터리를 모두 포함하여 디렉터리를 생성할 수 있습니다:

Path dir = Path.of("output/reports/2024");

// Creates all missing intermediate directories:
Files.createDirectories(dir);

// Creates a single directory (fails if parent missing):
Files.createDirectory(Path.of("output/reports/2025"));

임시 파일 및 디렉터리

임시 파일을 안전하게 생성하면 JVM이 정리할 수 있습니다:

// Temp file in default temp directory
Path tmp = Files.createTempFile("prefix_", ".txt");
Files.writeString(tmp, "temp data");
System.out.println(tmp); // something like /tmp/prefix_12345.txt

// Temp directory
Path tmpDir = Files.createTempDirectory("work_");
System.out.println(tmpDir);

Files.lines를 사용한 줄 스트리밍

Files.lines()는 지연 방식의 Stream<String>을 반환합니다. 모든 내용을 메모리에 적재하지 않으므로 대용량 파일에서는 readAllLines보다 적합합니다:

try (var stream = Files.lines(Path.of("large.log"))) {
    long errorCount = stream
        .filter(l -> l.contains("ERROR"))
        .count();
    System.out.println("Errors: " + errorCount);
} // stream (and underlying reader) closed automatically

클래스패스 리소스에서 읽기

getClass().getResourceAsStream()과 NIO 복사를 결합하여 리소스를 불러올 수 있습니다:

try (var in = getClass().getResourceAsStream("/config.json")) {
    Path tmp = Files.createTempFile("config", ".json");
    Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
    String json = Files.readString(tmp);
    System.out.println(json);
}

빠른 확인

대용량 로그 파일의 모든 줄을 동시에 메모리에 적재하지 않고 읽으려면 어떤 메서드를 사용해야 하나요?

복습: Files 유틸리티

핵심 내용:

  • Files.readString/readAllLines/readAllBytes — 전체 파일을 읽습니다
  • Files.writeString/write — 문자열 또는 줄을 씁니다
  • Files.copy/move와 StandardCopyOption — 복사, 이름 변경, 이동에 사용합니다
  • Files.delete/deleteIfExists — 안전하게 삭제합니다
  • Files.lines — 대용량 파일을 위한 지연 스트림입니다(try-with-resources를 사용하세요)

자주 묻는 질문

“Files 유틸리티: 읽기, 쓰기, 복사, 이동” 강의는 무료인가요?

네 — “Files 유틸리티: 읽기, 쓰기, 복사, 이동” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Java Academy 강의 전체를 잠금 해제할 수 있습니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“Files 유틸리티: 읽기, 쓰기, 복사, 이동”에서 뭘 배우나요?

일반적인 파일 작업에 Files.readString, writeString, copy, move, delete를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 Java Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Java Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Java Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“Files 유틸리티: 읽기, 쓰기, 복사, 이동” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Java Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Java Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Path: 파일 위치 표현
  2. Files 유틸리티: 읽기, 쓰기, 복사, 이동
  3. Files.walk로 디렉터리 트리 순회
  4. WatchService: 파일 변경 모니터링
← Java Academy(으)로 돌아가기