JAVA
File 객체 생성하기, 파일과 디렉토리 생성하기, 삭제하기
소힌
2022. 1. 21. 18:00
import java.io.File;
public class Main {
public static void main(String[] ars) {
File file = new File("c:\\aaaa\\bbbb.txt");
System.out.println("name : " + file.getName());
System.out.println("name : " + file.getPath());
System.out.println("name : " + file.isFile());
// 파일인지 여부를 참 거짓 값으로
File directory = new File("C:\\aaaa");
System.out.println("is file?" + directory.isFile());
System.out.println("is directory?" + directory.isDirectory());
// 파일은 디렉토리도 가질 수 있다
System.out.println("is exist?" + file.exists());
File whatthe = new File("C:\\aaaa\\qqqq.txt");
System.out.println(whatthe.getName());
System.out.println(whatthe.getPath());
System.out.println(whatthe.isFile());
System.out.println(whatthe.exists());
// 파일 객체는 실제 파일이 아니라 파일을 표현할 수 있는 객체일 뿐이다
// 실제하든 아니든 디렉토리든 파일을 표현만 하는 객체
}
}
1. getPath()
File 객체를 생성할 때 넣어준 경로를 그대로 반환
2. getAbsolutePath()
현재 프로그램을 실행한경로에 생성할때 넣어준 경로를 덧붙인 절대적인 경로를 보여준다
3. getCanonicalPath()
일반적(실제적인) 경로를 보여준다
4. .createNewFile()
이름 그대로 새 파일을 생성한다. 단 그 파일이 존재하는 경우에.
try {
if (file.createNewFile()) {
System.out.println("파일 생성 성공");
}
// 같은 이름의 파일이 없으면 true
// 이미 같은 이름의 파일이 있으면 false를 반환한다
} catch (IOException e) {
System.out.println("파일을 생성하는 중 io예외가 발생하였습니다");
}
createNewFile이라는 메소드 자체가 예외사항을 발생하는 경우가 있어
try catch문을 사용해주어야한다.
5. 폴더를 만들어 안에 파일 생성하기
import java.io.File;
import java.io.IOException;
public class Main3 {
public static void main(String[] args) {
File directory = new File(".\\myfolder");
directory.mkdir();
// 폴더가 만들어지면 true값을 반환
File myFile = new File(".\\\\myfolder\\\\myfile.txt");
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
System.out.println("예외가 발생하였습니다");
}
}
}
}
6. 파일의 이름을 변경하고 파일을 삭제하기
import java.io.File;
public class Main4 {
public static void main(String[] args) {
File file = new File(".\\test.txt");
// [1] 기존 파일 이름을 변경
file.renameTo(new File(".\\mytest2.txt"));
// [2] 파일 삭제하기
File myfile = new File(".\\myfolder\\myfile.txt");
myfile.delete();
}
}