JAVA/HIGH JAVA

[JAVA] 입출력( I/O ) - File객체

아잠만_ 2024. 5. 2. 12:50

File

파일과 디렉토리를 다루는데 사용되는 클래스

경로

절대경로 상대경로
파일의 root부터 해당 파일까지의 전체 경로(URL) 현재 파일의 위치를 기준으로 연결하는 파일의 상대적인 경로

/         root
./       현재 위치
../      상위 경로

E가 현재 위치한 폴더인 상태일 경우 F의 경로 나타내기

절대 경로 : /B/F/F.jpg
상대 경로 : ../../B/F/F.jpg

파일의 속성, 생성, 삭제, 목록

File객체 만들기

  1. new File(String 파일 또는 경로)
    ==> 디렉토리와 디렉토리 사이 또는 디렉토리와 파일명 사이의
           구분문자는 역슬래시('\') 또는 슬래쉬('/')를 사용할 수 있다.
  2. new File(String parent, String child)
    ==> 'parent' 디렉토리 안에 있는 'child'파일을 나타낸다
  3. new File(File parent, String child)

import java.io.File;

public class FileTest01 {
//		File file1 = new File("D:/D_Other/test.txt");	// 구분문자를 '/'로 사용
		File file1 = new File("D:\\D_Other\\test.txt");	// 구분문자를 '\'로 사용, 2개씩 작성할 것
		
		System.out.println("파일명 : "+file1.getName());	// 파일명 : test.txt
		System.out.println("파일일까? : "+file1.isFile());	// 파일일까? : true
		System.out.println("디렉토리일까? : "+file1.isDirectory()); // 디렉토리일까? : false
		System.out.println();

		File file2 = new File("d:/d_other");
		System.out.println("파일명 : "+file2.getName());	// 파일명 : d_other
		System.out.println("파일일까? : "+file2.isFile());	// 파일일까? : false
		System.out.println("디렉토리일까? : "+file2.isDirectory()); // 디렉토리일까? : true
		System.out.println();
		
		// 2. new File(String parent, String child)
		//		==> 'parent' 디렉토리 안에 있는 'child'파일을 나타낸다
		File file3 = new File("d:/d_other","test.txt");
		System.out.println("파일명 : "+file3.getName());	// 파일명 : test.txt
		System.out.println("파일일까? : "+file3.isFile());	// 파일일까? : true
		System.out.println("디렉토리일까? : "+file3.isDirectory()); // 디렉토리일까? : false
		System.out.println();
		
		// 3. new File(File parent, String child)
		File file4 = new File(file2, "test.txt");
		System.out.println("파일명 : "+file4.getName());	// 파일명 : test.txt
		System.out.println("파일일까? : "+file4.isFile());	// 파일일까? : true
		System.out.println("디렉토리일까? : "+file4.isDirectory()); // 디렉토리일까? : false
		System.out.println();
	}
}

디렉토리(폴더) 만들기

  1. mkdir() 
    ==> File객체에 지정한 전체 경로 중에서 마지막 위치의 디렉토리를 만든다.
    ==> 반환값 : 만들기 성공(true), 만들기 실패(false)
    ==> 중간의 경로가 모두 미리 만들어져 있어야 마지막 위치의 경로를 만들 수 있다.
    상위 디렉토리도 존재하지 않을 때는 mkdir()로 생성할 수 없음 ( mkdir()는 경로 중 맨 끝의 것만 생성 )
  2. mkdirs() 
    ==> 중간 부분의 경로가 없으면 중간 부분의 경로도 같이 만들어준다.

import java.io.File;

public class FileTest01 {
	public static void main(String[] args) {
		File file5 = new File("d:/d_other/연습용");
		System.out.println(file5.getName()+"의 존재 여부 : "+file5.exists()); // 연습용의 존재 여부 : false
		
		if(file5.mkdir()) {	// 만들기 성공이면  true
			System.out.println(file5.getName()+" 폴더가 생성되었습니다.");
		} else {	// 만들기 실패 false
			System.out.println("이미 "+file5.getName()+" 폴더가 존재합니다.");
		}
		System.out.println();
		
		File file6 = new File("d:/d_other/test/java/src");	
		System.out.println(file6.getName()+"의 존재 여부 : "+file6.exists()); // src의 존재 여부 : false

		// 상위 디렉토리도 존재하지 않을 때는 mkdir()로 생성할 수 없음
		// mkdir()는 경로 중 맨 끝의 것만 생성해주기 때문에 src폴더 생성 실패함
		// mkdirs()로 생성
		if(file6.mkdirs()) {	// 만들기 성공이면  true
			System.out.println(file6.getName()+" 폴더가 생성되었습니다.");
		} else {	// 만들기 실패 false
			System.out.println("이미 "+file6.getName()+" 폴더가 존재합니다.");	
		}
	}
}

파일과 디렉토리의 메소드들

  1. isFile()
    파일인지 확인 여부
  2. isDirectory()
    디렉토리인지 확인 여부
  3. isHidden()
    숨겨져있는지 확인 여부
  4. 읽기 쓰기 가능 여부
    1. canRead()
    2. canWrite()
  5. getName()
    파일이나 디렉토리의 이름을 출력
  6. length()
    파일 크기 출력
  7. lastModified()
    수정한 날짜 출력
  8. getPath()
    경로를 나타냄
  9. getAbsolutePath()
    절대 경로를 나타냄
  10. exists()
    파일이나 디렉토리 존재여부 확인
  11. createNewFile()
    파일 생성
    반환값 : true(생성 성공) / false (생성 실패)
  12. 디렉토리에 존재하는 파일과 디렉토리의 목록 뽑아내기
    1. list()
      전체 목록 String 배열로 뽑아내기
      폴더와 파일 구별이 되지 않음
    2. listFiles()
      전체 목록 File 배열로 뽑아내기
      isFile()과, isDirectory()를 통해 폴더와 파일 구별가능

import java.io.File;
import java.io.IOException;

public class FileTest02 {
	public static void main(String[] args) {
		File f1 = new File("d:/d_other/test.txt");
		
		System.out.println(f1.getName()+"의 크기 : "+f1.length()+"byte(s)");	// test.txt의 크기 : 52byte(s)
		System.out.println("path : "+f1.getPath()); // path : d:\d_other\test.txt
		// 절대 경로
		System.out.println("absolutePath : "+f1.getAbsolutePath()); // absolutePath : d:\d_other\test.txt
		System.out.println();
		
		// 현재 위치 나타내기
		File f2 = new File(".");
		System.out.println("path : "+f2.getPath()); // path : .
		System.out.println("absolutePath : "+f2.getAbsolutePath()); 
		// absolutePath : D:\A_TeachingMaterial\03_HighJava\workspace\javaIOTest\.
		System.out.println();
		
		if(f1.isFile()) {	// test.txt은 파일입니다.
			System.out.println(f1.getName()+"은 파일입니다.");
		} else if(f1.isDirectory()){
			System.out.println(f1.getName()+"은 디렉토리입니다.");
		} else {
			System.out.println(f1.getName()+"은 뭘까?");
		}
		System.out.println();
		
		if(f2.isFile()) {	// .은 디렉토리입니다.
			System.out.println(f2.getName()+"은 파일입니다.");
		} else if(f2.isDirectory()){
			System.out.println(f2.getName()+"은 디렉토리입니다.");
		} else {
			System.out.println(f2.getName()+"은 뭘까?");
		}
		System.out.println();
		
		File f3 = new File("d:/d_other/sample.txt");
		// 없는 파일이므로 file도 directory도 아님
		if(f3.isFile()) {	// sample.txt은 뭘까?
			System.out.println(f3.getName()+"은 파일입니다.");
		} else if(f3.isDirectory()){
			System.out.println(f3.getName()+"은 디렉토리입니다.");
		} else {
			System.out.println(f3.getName()+"은 뭘까?");
		}
		System.out.println();
		
		if(f3.exists()) {
			System.out.println(f3.getName()+"은 존재합니다.");
		} else {
			try {
				if(f3.createNewFile()) { // sample.txt파일을 새로 만들었습니다
					System.out.println(f3.getName()+"파일을 새로 만들었습니다");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println();
		
		File f4 = new File("d:/d_other");
		// 전체 목록 배열로 가져오기
		String[] fileArr = f4.list();
		for(String strFile : fileArr) {
			System.out.println(strFile);
		}
		System.out.println();
		/*
		 * sample.txt 
		 * test 
		 * test.txt 
		 * 연습용
		 */
		
		File[] fileArr2 = f4.listFiles();
		for(File file : fileArr2) {
			System.out.print(file.getName()+" ==> ");
			if(file.isFile()) {
				System.out.println("파일");
			} else if(file.isDirectory()) {
				System.out.println("디렉토리");
			} 
		}
		/*
		 * sample.txt ==> 파일 
		 * test ==> 디렉토리 
		 * test.txt ==> 
		 * 파일 연습용 ==> 디렉토리
		 */
	}
}

모든 파일 및 디렉토리 목록 출력

cmd에 dir을 치면 현재 위치한 디렉토리와 파일이름이 뜬다 이와 같은 자바 시스템을 만들어보기


package kr.or.ddit.basic;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileTest03 {
	public static void main(String[] args) {
		FileTest03 test = new FileTest03();
		File d = new File("D:/D_Other");
		test.dir(d);
	}

	// 디렉토리 정보를 매개변수로 받아서 해당 디렉토리에 있는
	// 모든 파일 및 디렉토리 목록을 출력하는 메서드
	public void dir(File d) {
		if(!d.isDirectory()) { // 목록을 출력할 것이므로 파일인 것은 제외
			System.out.println("디렉토리(폴더)만 가능합니다");
			return;
		}
		
		System.out.println("[" + d.getAbsolutePath() + "] 디렉토리 내용");
		
		// 해당 디렉토리 안에 있는 모든 파일 및 디렉토리 정보를 가져온다.
		File[] files = d.listFiles();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd a HH:mm");
		
		// 가져온 파일과 디렉토리 목록 개수만큼 반복 처리
		for(File file : files) {
			String fileName = file.getName();
			String attr = ""; // 파일의 속성 (읽기, 쓰기, 히든, 디렉토리)
			String size = "";
			if(file.isDirectory()) {
				attr = "<DIR>";
			} else if(file.isFile()) {
				size = file.length()+"";
				attr += file.canRead() ? "R" : "";
				attr += file.canWrite() ? "W" : "";
				attr += file.isHidden() ? "H" : "";
			} 
			String strDate = df.format(new Date(file.lastModified()));
			System.out.printf("%s\t%5s\t%12s\t%s\n",strDate,attr,size,fileName);
		}
	}

}