버글버글

Java 수업 기록 (21) IO - File 본문

java/java 수업 기록

Java 수업 기록 (21) IO - File

Bugle 2022. 8. 13. 00:00
반응형

▶ IO 

▶ File 

1. 패키지 : java.io
2. 파일 및 디렉터리 관리

생성 방법
1) new File(경로, 파일)
2) new File(파일)

3. 윈도우의 경로 구분 방법 : 백슬래시 (\)
4. 리눅스의 경로 구분 방법 : 슬래시(/)

java.io.file

 

*폴더(디렉터리) 만들기(예시)

		File dir = new File("C:", storage");

		// 존재하지 않으면 만들겠다.
		if(dir.exists() == false) {	// 동일한 역할 if(!dir.exists())
			dir.mkdirs();
		}
		// 존재하면 삭제하겠다.
		else {
			dir.delete();			// 지금 지운다.
			dir.deleteOnExit(); 	// JVM이 종료되면 지운다.
		}

- 명령어를 실행 할 때마다 생성되고 삭제 된다

 

*파일만들기 

		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.getParent());
		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 dir = new File("F:\\gdj\\GDJ");
		
		File[] list = dir.listFiles();
		for(int i = 0; i < list.length; i++) {
			System.out.println(list[i].getName());
		}
new DecimalFormat("#,##0") 을 붙이면 숫자 천 단위마다 쉼표(,)를 붙여준다.

*디렉토리 내용 상세보기

		
		File dir = new File("F:\\gdj\\GDJ\\javastudy");
		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("yyy-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) + "바이트");

*디렉토리 + 파일 삭제

	String sep = File.separator;
		
		File file = new File("c:" + sep + "storage", "mytxt");
		if(file.exists()) {
			file.delete();
		}
		
		File dir = new File("C:" + sep + "storage");
		
		if(dir.exists()) {
			dir.delete();
		}

 

반응형