[IO-1] File

seratpfk·2022년 8월 11일
0

JAVA

목록 보기
88/96

File 클래스

  1. 패키지 : java.io
  2. 파일 및 디렉터리 관리
  3. 생성 방법
    1) new File(경로, 파일)
    2) new File(파일)
  4. 자바의 경로 구분 방법 : 백슬래시()
  5. 리눅스의 경로 구분 방법 : 슬래시(/)
  • 폴더 만들기
		// 폴더(디렉터리) 만들기
		File dir = new File("c:\\storage");
		// 존재하지 않으면 만들겠다.
		if(dir.exists() == false) {  // if(!dir.exists())
			dir.mkdirs();
		}
		// 존재하면 삭제하겠다.
		else {
			dir.delete(); // 지금 지운다.
			dir.deleteOnExit(); // JVM이 종료되면 지운다.
		}
  • txt 파일 생성
		File file = new File("c:\\storage", "my.txt");
		try {
			if(file.exists() == false) {
				file.createNewFile();
			} 
			else {
				file.delete();
			}
		} catch(IOException e) {
			// 개발할 때 넣는 catch 블록 코드
			e.printStackTrace(); // 에러를 콘솔에 찍어라.
		}
  • 전체 경로, 디렉터리, 파일
		File file = new File("c:\\storage", "my.txt");
	    System.out.println("파일명 : " + file.getName());
		System.out.println("전체경로(경로 + 파일명) : " + file.getPath());
		System.out.println("디렉터리인가? " + file.isDirectory());
		System.out.println("파일인가? " + file.isFile());
		long lastModifiedDate = file.lastModified();
		System.out.println("수정한 날짜 : " + lastModifiedDate);
		String lastModified = new SimpleDateFormat("a hh:mm yyyy-MM-dd").format(lastModifiedDate);
		System.out.println("수정한 날짜 : " + lastModified);
		long size = file.length(); // 바이트 단위
		System.out.println(size + "byte");
  • 디렉터리 내부의 모든 파일/디렉터리를 File 객체로 가져오기
		File dir = new File("C:\\GDJ"); // C:\\GDJ
		File[] list = dir.listFiles(); 
		for(int i = 0; i < list.length; i++) {
			System.out.println(list[i].getName());
		}
  • 플랫폼마다 다른 경로 구분자 지원
		File file = new File("c:" +File.separator+ "storage" +File.separator+ "my.txt");
		System.out.println(file.getName());
  • C:\storage 디렉터리 조회
	public static void q1() {
		File dir = new File("C:\\GDJ");
		File[] list = dir.listFiles();
		int dirCnt = 0;
		int fileCnt = 0;
		long totalSize = 0;
		for(File file : list) {
			if(file.isHidden()) {
				continue;
			}
			String lastModified = new SimpleDateFormat("yyyy-MM-dd a hh:mm").format(file.lastModified());
			String directory = ""; 
			String size = "";
			if(file.isDirectory()) {
				directory = "<DIR>";
				size = "     ";
				dirCnt++;
			} else if(file.isFile()) {
				directory = "     ";
				size = new DecimalFormat("#,##0").format(file.length()) + "";
				fileCnt++;
				totalSize += Long.parseLong(size.replace(",", ""));
			}
			String name = file.getName();
			System.out.println(lastModified + " " + directory + " " + size + " " + name);
		}
		System.out.println(dirCnt + "개 디렉터리");
		System.out.println(fileCnt + "개 파일 " + new DecimalFormat("#,##0").format(totalSize) + "바이트");	
	}
  • C:\storage 디렉터리 삭제하기
	public static void q2() {
		// 디렉터리가 비어 있어야 삭제할 수 있으므로 내부 파일을 먼저 삭제
		String sep = File.separator;
		File file = new File("C:" + sep + "storage", "my.txt");
		if(file.exists()) {
			file.delete();
		}
		File dir = new File("C:" + sep + "storage");
		if(dir.exists()) {
			dir.delete();
		}
	}

0개의 댓글