다연이네

[days25] File 객체 본문

Java

[days25] File 객체

 다연  2020. 10. 25. 15:28
반응형

File 객체는 입출력의 대상이 되기 때문에 많이 쓰인다.
파일일수도 있고, 디렉토리일수도 있다.

 

파일 객체의 메소드 알아보기

package test;

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

public class Re05 {

	public static void main(String[] args) throws IOException {
		
		
		//C:\\Users\\82103\\Pictures\\Saved Pictures\\cloud.jpg
		
		//File file = new File(File parent, String child);
		
		File parent = new File("C:\\Users\\82103\\Pictures\\Saved Pictures\\");
		String child = "cloud.jpg";
				
		File file  = new File(parent, child);
		
		System.out.println(file.exists()); //존재하니?
		System.out.println(file.isDirectory()); //디렉토리니?(폴더니?) false
		System.out.println(file.isFile()); //파일이니? true
		System.out.println(file.canExecute()); //실행할 수 있는 파일이니? true
		System.out.println(file.canRead()); //읽을 수 있는 파일이니? true
		System.out.println(file.canWrite()); //쓸 수 있는 파일이니? true
		System.out.println(file.isHidden()); //숨김 파일이니? false

		System.out.println(file.lastModified()); //마지막에 수정된 날짜
		
		System.out.println(file.getName()); //cloud.jpg (파일명)
		System.out.println(file.getPath()); //C:\Users\82103\Pictures\Saved Pictures\cloud.jpg (전체경로)
		System.out.println(file.getParent()); //C:\Users\82103\Pictures\Saved Pictures (파일명을 제외한 조상 디렉터리)
		
		
		System.out.println(file.getAbsolutePath());		//C:\Users\82103\Pictures\Saved Pictures\cloud.jpg
		System.out.println(file.getCanonicalPath());	//C:\Users\82103\Pictures\Saved Pictures\cloud.jpg
		//AbsolutePath() 절대경로를 파일객체로 반환
		//CanonicalPath() 정규경로로 String 반환
		//차이점 ? 경로를 상대경로로 바꿔서 돌리면 결과가 다르다
		//상대경로 그대로(말이 안됨) / 제대로 나옴
	}

}

 

문서 위치에 있는 모든 File(디렉토리, 파일) 최종수정일과 용량 출력하기

package test;

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

public class Re05 {

	public static void main(String[] args) {
		
		String pathname = "C:\\Users\\82103\\Documents"; 
		File file = new File(pathname); // pathname 위치의 파일
	
		String [] list = file.list(); //file.list : 파일 이름들만 가져오기 - 파일명
											// file.listFiles() 파일 객체들 가져오기 - C:\Users\82103\Documents\파일명
		
		
		for (int i = 0; i < list.length; i++) {
			File f = new File(pathname, list[i]);
            				//parent(경로), child(파일명)
			
			if(f.isDirectory()) System.out.print("[폴더]");
			else if(f.isFile()) System.out.print("[파일]");
			
			System.out.printf("%s\t%s\t %d(bytes)\n",
	 				new Date(f.lastModified()).toLocaleString(), f.getName(), f.length());

		}
	
		
		
	}

}

 

 

출력값

학생명단.txt 불러와 폴더 내 폴더 만들기

[양식]

20201023(금) 
 ㄴ 1조
  ㄴ각 이름 파일
 ㄴ 2조
  ㄴ
   :
   :

-------------------------

학생명단.txt

1조 - 이름/이름/이름/이름 
2조 -            "
3조 -            "
4조 -            "

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Re05 {

	public static void main(String[] args) {
		
		/* 흐름
		File f1 = new File(f, "1조");
		
		File f2 = new File(f1, "배다연");
				ssf.mkdirs();
		*/

	
		String parent = "C:\\Users\\82103\\Documents";
		
		LocalDate now = LocalDate.now();
		String pattern = "yyyyMMdd(E)";
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
		String child = dtf.format(now);
		
		File f1 = new File(parent, child);
		
		if(f1.exists()) f1.delete(); //이전에 만들어진 파일 있으면 삭제하겠다
		
		String fileName= ".\\src\\days25\\학생명단.txt";
		try(
				FileReader fr = new FileReader(fileName);
				BufferedReader br = new BufferedReader(fr)
						) {
			
			String line = null;
			String regex = "\\s*-\\s*|/";
			while((line=br.readLine())!=null) {
				String [] teamvalues = line.split(regex);
				String teamname = teamvalues[0];
				
				File f2 = new File(f1, teamname);
				
				for (int i = 1; i < teamvalues.length; i++) {
					File f3 = new File(f2, teamvalues[i]);
					f3.mkdirs(); //이거에 의해서 실제 폴더들이 만들어짐
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

}

 

 

 

 

반응형
Comments