개발 기록이
[JAVA] File, Files 클래스 정리 본문
1. File 클래스
File 클래스는 파일 및 디렉토리를 생성하고 존재 여부를 확인하는 기능을 제공한다.
File file = new File("test.txt");
경로값으로는 상대경로/절대경로를 입력해 주면 된다.
// 상대경로
File relativePath = new File("test.png");
// 절대경로
Path absolutePath1 = Paths.get("D:\\test\\test.png"); // Windows
Path absolutePath2 = Paths.get("/home/user/test.png"); // Linux
대표적인 메서드를 살펴보자.
1) file.createNewFile() : 새로운 파일 생성
- 이미 해당 경로에 파일이 존재하는 경우 false를 반환한다.
File file = new File("D:\\test\\test.png");
boolean newFile = file.createFile(); // 파일 생성
if(newFile) {
System.out.println("파일 생성 성공"); // true
} else {
System.out.println("이미 D:\test 경로에 해당 파일이 존재함"); // false
}
2) file.mkdir() : 디렉토리 생성
File dir = new File("C:\\testDir");
if(dir.mkdir()) {
System.out.println("디렉토리 생성 완료"); // true
} else {
System.out.println("디렉토리 생성 실패"); // false
}
3) file.exists() : 파일 또는 디렉토리 존재 여부 확인
File file = new File("C:\\testDir\\test.png");
if(file.exists()) {
System.out.println("파일 또는 디렉토리가 존재함");
} else {
System.out.println("파일 또는 디렉토리가 존재하지 않음");
}
4) file.getName() : 파일 이름 조회
File file = new File("C:\\testDir\\test.png");
System.out.println("파일 이름: " + file.getName()); // test.png
5) file.getPath() : 파일 경로 조회
File file = new File("C:\\testDir\\test.png");
System.out.println("파일 경로: " + file.getPath()); // C:\\testDir\\test.png
6) file.getAbsolutePath() : 파일 절대 경로
File file = new File("C:\\testDir\\test.png");
System.out.println("파일 절대 경로: " + file.getAbsolutePath()); // C:\\testDir\\test.png
7) file.length() : 파일 크기(bytes 단위)
8) file.lastModified() : 파일의 마지막 수정 시간을 Date 타입으로 반환함
9) file.delete() : 파일 또는 디렉토리 삭제
// 삭제할 파일 경로
File file = new File("C:\\testDir\\test.png");
if (file.exists()) {
if (file.delete()) {
System.out.println("파일 삭제 성공");
} else {
System.out.println("파일 삭제 중 오류 발생");
}
} else {
System.out.println("파일이 존재하지 않음";
}
10) file.renameTo() : 파일 이름 변경
File file = new File("test.txt");
File newFile = new File("newTest.txt");
if (file.renameTo(newFile)) {
System.out.println("파일 이름 변경");
}
11) file.list() : 디렉토리 내 파일 목록 조회
File dir = new File("testDir");
String[] files = dir.list(); //문자열 배열 반환
if (files != null) {
for (String fileName : files) {
System.out.println(fileName);
}
}
12) file.listFiles() : 디렉토리 내 파일과 디렉토리 객체 목록 조회
- 파일 및 디렉토리에 대한 상세 정보를 조회할 수 있다.
File dir = new File("C:/testDir");
// testDir 디렉토리 내의 파일 및 디렉토리에 대한 File 객체 배열을 반환
File[] fileList = dir.listFiles();
if (fileList != null) {
for (File file : fileList) {
System.out.println("파일명: " + file.getName());
System.out.println("절대 경로: " + file.getAbsolutePath());
System.out.println("파일 크기 (bytes): " + file.length());
System.out.println("마지막 수정 시간: " + file.lastModified());
if (file.isDirectory()) { // 디렉토리인지 체크
System.out.println("디렉토리입니다.");
} else if (file.isFile()) { // 파일인지 체크
System.out.println("파일입니다.");
}
}
}
2. Files 클래스
Java 7 버전부터 사용이 가능한 클래스이며, Files의 객체는 매개값으로 Path 객체를 받는다.
Paths.get(문자열) 은 문자열을 Path 객체로 변환해준다.
Path beforePath = Paths.get("C:\\testDir\\before.txt"); //복사할 원본 파일 경로
Path afterPath = Paths.get("C:\\testDir\\after.txt"); //복사된 파일의 목적지 경로
1) Files.copy(beforePath, afterPath, CopyOption) : 파일 복사
- before.txt 파일을 after.txt로 복사하며, 만약 after.txt가 이미 존재하면 덮어쓴다.
Path beforePath = Paths.get("C:\\testDir\\before.txt"); //복사할 원본 파일 경로
Path afterPath = Paths.get("C:\\testDir\\after.txt"); //복사된 파일의 목적지 경로
try {
// 파일 복사 (기존 파일이 있으면 덮어쓰기)
Files.copy(beforePath, afterPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("파일 복사 성공");
} catch (IOException e) {
System.out.println("파일 복사 실패");
}
// StandardCopyOption.REPLACE_EXISTING : 복사된 경로에 이미 파일이 존재하는 경우 덮어쓰기 허용 옵션
2) Files.move(beforePath , afterPath , CopyOption) : 파일 이동 및 파일명 변경
- before.txt 파일을 newFolder 디렉토리로 이동시키거나 이름을 변경한다.
Path beforePath = Paths.get("C:\\testDir\\before.txt");
Path afterPath = Paths.get("C:\\testDir\\newPath\\after.txt");
try {
// 파일 이동 (기존 파일이 있으면 덮어쓰기)
Files.move(beforePath, afterPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("파일 이동 성공");
} catch (IOException e) {
System.out.println("파일 이동 실패");
}
3) Files.delete(Path) : 파일 삭제
Path deletePath = Paths.get("C:\\testDir\\test.txt");
try {
Files.delete(deletePath);
System.out.println("파일 삭제 성공");
} catch (IOException e) {
System.out.println("파일 삭제 실패");
}
4) Files.exists(Path) : 파일 존재 여부 확인
Path path = Paths.get("C:\\testDir\\existingFile.txt");
if (Files.exists(path)) {
System.out.println("파일이 존재함);
} else {
System.out.println("파일이 존재하지 않음");
}
출처: OpenAI ChatGPT (https://openai.com), https://rebugs.tistory.com/423
'웹 개발 > Back-end' 카테고리의 다른 글
[JAVA] QRCode 이미지 생성하기 (0) | 2024.06.02 |
---|---|
[JAVA] 파일 다운로드 url 생성하기 (0) | 2024.05.25 |
[웹개발] 파일기능(2) MultipartFile와 MultipartHttpServletRequest 로 파일 저장하기 (0) | 2024.04.13 |
[SpringBoot] @Controller redirect 하기 (0) | 2024.03.30 |
[JAVA] 자바 스트림 사용하기(map, filter, sorted) (0) | 2023.11.19 |