경계의 경계

자바의 파일 입출력 본문

Java

자바의 파일 입출력

gigyesik 2024. 2. 9. 12:38

Intro

파일 입출력은 자바 프로그램 내에서 파일을 어떻게 읽고(Reading), 쓰고(Creating), 수정하고(Updating), 삭제하는지(Deleteing) 에 대한 방법론이다.

자바의 대표적인 파일 입출력 API 에는 file과 path 가 있다.

각 API 에 대해서 모두 정리하는 것보다는 문서를 보는 것이 메서드 이해가 되므로, 기본적인 케이스만 정리한다.

Path API (java.nio.file.Path)

자바 1.7 에 추가된 API

Basic

아래의 여러 Path.of() 출력은 전부 readme.txt 의 경로를 반환한다.

Path path = Path.of("c:\\\\dev\\\\licenses\\\\windows\\\\readme.txt");
System.out.println(path);

path = Path.of("c:/dev/licenses/windows/readme.txt");
System.out.println(path);

path = Path.of("c:" , "dev", "licenses", "windows", "readme.txt");
System.out.println(path);

path = Path.of("c:" , "dev", "licenses", "windows").resolve("readme.txt");
System.out.println(path);

path = Path.of(new URI("file:///c:/dev/licenses/windows/readme.txt"));
System.out.println(path);

path = Paths.get("c:/dev/licenses/windows/readme.txt");
System.out.println(path);

Create

path = Path.of("/src/fundamental");
Path newDirectory;
if (!Files.exists(path)) {
    newDirectory = Files.createDirectories(path.resolve("pathapi"));
} else {
    newDirectory = path.resolve("pathapi");
}
System.out.println("newDirectory = " + newDirectory);

Path newFile;
if (!Files.exists(newDirectory.resolve("pathtest.txt"))) {
    newFile = Files.createFile(newDirectory.resolve("pathtest.txt"));
} else {
    newFile = newDirectory.resolve("pathtest.txt");
}
System.out.println("newFile = " + newFile);

File API (java.io.File)

File file = new File("filetest.txt");
file.createNewFile();

file.exists(); // true
file.getAbsolutePath();
file.getName(); // filetest.txt

Resources

'Java' 카테고리의 다른 글

자바의 메모리 관리  (1) 2024.02.13
자바의 HTTP 통신 라이브러리  (0) 2024.02.09
자바의 객체 지향 프로그래밍  (0) 2024.02.06
자바의 캡슐화  (2) 2024.02.06
자바의 추상화  (1) 2024.02.06