본문 바로가기

JAVA

File

파일 관련된 메소드들

// File

String path = "C:\\Users\\jungmo\\eclipse-workspace\\javastudy20230828\\src\\ch18IO\\lecture\\C28file.java";
File file = new File(path);

// 크기
// file.length()
System.out.println(file.length());

// 있는지?
// file.exists()
System.out.println(file.exists());

// 경로
// getPath()
System.out.println(file.getPath());

// 마지막 수정일시
// lastModified()
System.out.println(file.lastModified());
// 날짜로 변경하고 싶으면 java long to date 검색해서 보기
System.out.println(new Date(file.lastModified()));

 

디렉토리에 관련된 메소드들

String path = "C:/Temp/CodeStudy";
File file = new File(path);

// 디렉토리(폴더)인지 ?
System.out.println(file.isDirectory());

// 디렉토리내에 있는 파일목록 얻기
// File 타입으로 변수 생성 해서 향상된for문 돌리기
for(File list: file.listFiles()){
    System.out.println("파일경로 + 파일명: " + list);
    System.out.println("파일이름만: " + list.getName()); // 파일명만 얻고 싶은 경우
}

 

// 존재하지 않은 디렉토리
String path2 = "C:/Temp/CodeStudy/Test";
File file2 = new File(path2);

 

// 디렉토리 존재유무
// 없으니깐 false
System.out.println(file2.exists());

// 디렉토리 만들기
// 만약 path2 디렉토리가 없으면 Test라는 디렉토리를 만들어라
if(!file2.exists()){
    file2.mkdir(); // 디렉토리 만들기 mkdir()
}

 

여러개의 디렉토리를 만들고 싶다면

// mkdires
// 여러 디렉토리 한번에 만들기
// test1/test2/test3은 현재 없는 폴더이다 
String path = "C/Temp/CodeStudy/test1/test2/test3";
File file = new File(path);

System.out.println(file.exists());
if (!file.exists()) {
    file.mkdirs();
}
반응형