반응형

 

File 객체 만들기

 

 

1. new File(String 파일 또는 경로명)
=> 디렉토리와 디렉토리 사이 또는 디렉토리와 파일명 사이의 구분문자는 '\'를 사용하거나 '/'를 사용할 수 있다.

 

 

2. new File(File parent, String child)
=> 'parent' 디렉토리 안에 있는 'child' 파일 또는 디렉토리를 위한 파일 객체 생성

 

 

3. new File(String parent, String child)

 

 

 

  • 사용법
사용법
file.getName() 파일의 이름 확인
file.isFile() 파일 여부 확인
file.isDirectory() 디렉토리 여부 확인
file.length() 용량의 크기 (bytes)
file.getAbsolutePath() 절대 경로 (<=> 상대 경로: .이나 ..으로 시작함)
드라이브 문자로 시작함
file.getPath() File 객체를 생성할 때 넣어준 경로
file.getCanonicalPath() 표준 경로
=> 점(.)이나 상대경로에서 사용하는 현재 경로(.), 상위 경로(..)를 제외하여 최종 경로를 계산하여 알려줌

 

 

 

  • 파일 생성
package kr.or.ddit.basic;

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

public class T01FileTest {
	public static void main(String[] args) throws IOException {
		// File 객체 만들기 연습
		// 1. new File(String 파일 또는 경로명)
		//	  => 디렉토리와 디렉토리 사이 또는 디렉토리와 파일명 사이의 구분문자는 '\'를
		//		 사용하거나 '/'를 사용할 수 있다.
		File file = new File("d:/D_Other/test.txt"); // 경로에 맞춰서 미리 만들어놔야함
		System.out.println("파일명 : " + file.getName());
		System.out.println("파일 여부 : " + file.isFile());
		System.out.println("디렉토리(폴더) 여부 : " + file.isDirectory());
		System.out.println("------------------------------------------");
		
		File file2 = new File("d:/D_Other");
		System.out.println(file2.getName() + "은 ");
		if(file2.isFile()) {
			System.out.println("파일입니다.");
		} else if(file2.isDirectory()) {
			System.out.println("디렉토리(폴더) 입니다.");
		}
		System.out.println("------------------------------------------");
		
		// 2. new File(File parent, String child)
		// => 'parent' 디렉토리 안에 있는 'child' 파일 또는 디렉토리를 위한 파일 객체 생성
		File file3 = new File(file2, "test.txt");
		System.out.println(file3.getName() + "의 용량 크기 : " 
							+ file3.length() + "(bytes)");
		
		// 3. new File(String parent, String child)
		File file4 = new File(".\\D_Other\\test\\..", "test.txt");
		System.out.println("절대 경로 :" + file4.getAbsolutePath());
		System.out.println("경로 : " + file4.getPath());
		System.out.println("표준 경로 : " + file4.getCanonicalPath());
	}
}

 

결과 화면1

 

 

 

디렉토리 생성

 

 

  • 사용법
사용법
mkdir() File객체의 경로 중 마지막 위치의 디렉토리 만듦.
중간의 경로가 만들어져 있어야 함
mkdirs() 중간의 경로가 없으면 중간의 경로도 새롭게 생성한 후 마지막 위치의 디렉토리 만듦.


=> 위 두 메서드 모두 만들기에 성공하면 true, 실패하면 false 반환한다.

 

 

package kr.or.ddit.basic;

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

public class T01FileTest {
	public static void main(String[] args) throws IOException {
		/*
		 * 디렉토리(폴더) 만들기
		 * 
		 * 1. mkdir() => File객체의 경로 중 마지막 위치의 디렉토리를 만든다.
		 * 				  중간의 경로가 모두 미리 만들어져 있어야 한다.
		 * 
		 * 2. mkdirs() => 중간의 경로가 없으면 중간의 경로도 새롭게 생성한 후 마지막 위치의 디렉토리를
		 * 				    만들어 준다.
		 * 
		 * => 위 두 메서드 모두 만들기에 성공하면 true, 실행하면 false 반환한다.
		 */
		
		File file5 = new File("d:/D_Other/연습용");
		if(file5.mkdir()) {
			System.out.println(file5.getName() + " 만들기 성공!");
		} else {
			System.out.println(file5.getName() + " 만들기 실패!!!");
		}
		
		File file6 = new File("d:/D_Other/test/java/src");
		if(file6.mkdir()) {
			System.out.println(file6.getName() + " 만들기 성공!");
		} else {
			System.out.println(file6.getName() + " 만들기 실패!!!");
		}
	}
}

 

결과 화면2 : mkdir() 사용

 

 

package kr.or.ddit.basic;

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

public class T01FileTest {
	public static void main(String[] args) throws IOException {
		/*
		 * 디렉토리(폴더) 만들기
		 * 
		 * 1. mkdir() => File객체의 경로 중 마지막 위치의 디렉토리를 만든다.
		 * 				  중간의 경로가 모두 미리 만들어져 있어야 한다.
		 * 
		 * 2. mkdirs() => 중간의 경로가 없으면 중간의 경로도 새롭게 생성한 후 마지막 위치의 디렉토리를
		 * 				    만들어 준다.
		 * 
		 * => 위 두 메서드 모두 만들기에 성공하면 true, 실행하면 false 반환한다.
		 */
		
		File file5 = new File("d:/D_Other/연습용");
		if(file5.mkdirs()) {
			System.out.println(file5.getName() + " 만들기 성공!");
		} else {
			System.out.println(file5.getName() + " 만들기 실패!!!");
		}
		
		File file6 = new File("d:/D_Other/test/java/src");
		if(file6.mkdirs()) {
			System.out.println(file6.getName() + " 만들기 성공!");
		} else {
			System.out.println(file6.getName() + " 만들기 실패!!!");
		}
	}
}

 

결과 화면3 : 연습용은 미리 만들어져 있으니 실패가 뜸

 

 

 

응용

 

 

  • 사용법
사용법
exists() 파일이 있는지 확인
있으면 true,  없으면 false
listFiles() 해당 폴더에 있는 파일의 종류를 리턴
list() 해당 폴더에 있는 파일의 이름을 리턴
canRead() 파일 읽기 가능하면 true, 아니면 false 반환
canWrite() 파일 쓰기 가능하면 true, 아니면 false 반환
isHidden() 파일 숨김 속성이면 true, 아니면 false 반환

 

 

 

  • 파일 있는지 확인
package kr.or.ddit.basic;

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

public class T02FileTest {
	public static void main(String[] args) throws IOException {
		File f1 = new File("d:/D_Other/sample.txt");
		File f2 = new File("d:/D_Other/test.txt");
		
		if(f1.exists()) {
			System.out.println(f1.getAbsolutePath() + " 은 존재합니다.");
		} else {
			System.out.println(f1.getAbsolutePath() + " 은 없는 파일입니다.");
			
			if(f1.createNewFile()) {
				System.out.println(f1.getAbsolutePath() + " 파일을 생성했습니다.");
			}
		}
		
		if(f2.exists()) {
			System.out.println(f2.getAbsolutePath() + " 은 존재합니다.");
		} else {
			System.out.println(f2.getAbsolutePath() + " 은 없는 파일입니다.");
		}
	}
}

 

결과 화면4 : exists() 를 사용하면 파일이 있는지 없는지 확인할 수 있음

 

 

 

  • 폴더 안 파일 리스트 확인
package kr.or.ddit.basic;

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

public class T02FileTest {
	public static void main(String[] args) throws IOException {
		File f3 = new File("d:/D_Other");
		File[] files = f3.listFiles(); // 파일의 종류를 리턴
		for (File f : files) {
			System.out.print(f.getName() + " => ");
			if(f.isFile()) {
				System.out.println("파일");
			} else if(f.isDirectory()) {
				System.out.println("디렉토리(폴더)");
			}
		}
		System.out.println("====================================================");
		String[] fileNames = f3.list(); // 해당 폴더에 있는 파일의 이름을 리턴
		for (String fileName : fileNames) {
			System.out.println(fileName);
		}
		System.out.println("------------------------------------------------");
		System.out.println();
	}
}

 

결과 화면5 : listFiles(), list() 차이

 

 

package kr.or.ddit.basic;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class T02FileTest {
	public static void main(String[] args) throws IOException {
		displayFileList(new File("d:/D_Other"));
	}
	
	
	// 지정된 디렉토리(폴더)에 포함된 파일 및 디렉토리 목록을 보여주기 위한 메서드
	public static void displayFileList(File dir) {
		System.out.println("[" + dir.getAbsolutePath() + "] 디렉토리의 내용");
		
		// 디렉토리 안의 모든 파일 목록을 가져온다.
		File[] files = dir.listFiles();
		
		// 하위 디렉토리의 인덱스 정보를 저장하기 위한 List 객체 생성
		List<Integer> subDirIndexList = new ArrayList<Integer>();
		
		// 날짜 정보를 출력하기 위한 포맷터 생성
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a hh:mm");
		
		for(int i=0; i<files.length; i++) {
			String attr = ""; // 파일의 속성정보(읽기, 쓰기, 숨김파일, 디렉토리 구분)
			String size = ""; // 파일 크기
			
			if(files[i].isDirectory()) {
				attr = "<DIR>";
				subDirIndexList.add(i); // subDirIndexList의 사이즈는 디렉토리의 갯수
			} else {
				size = files[i].length() + "";
				attr = files[i].canRead() ? "R" : " ";  // 읽을 수 있는지
				attr += files[i].canWrite() ? "W" : " ";  // 쓸 수 있는지
				attr += files[i].isHidden() ? "H" : " ";  // 숨김 파일인지
			}
			
			System.out.printf("%s %5s %12s %s\n", 
								sdf.format(new Date(files[i].lastModified())),
								attr, size, files[i].getName());
		} // for문 끝
		
		int dirCount = subDirIndexList.size(); // 폴더 안의 하위 폴더 개수
		int fileCount = files.length - dirCount; // 폴더 안의 파일 개수
		
		System.out.println(fileCount + " 개의 파일, " + dirCount + " 개의 디렉토리");
		
		System.out.println();
	}
}

 

결과 화면6

 

 

package kr.or.ddit.basic;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class T02FileTest {
	public static void main(String[] args) throws IOException {
		displayFileList(new File("d:/D_Other"));
	}
	
	
	// 지정된 디렉토리(폴더)에 포함된 파일 및 디렉토리 목록을 보여주기 위한 메서드
	public static void displayFileList(File dir) {
		System.out.println("[" + dir.getAbsolutePath() + "] 디렉토리의 내용");
		
		// 디렉토리 안의 모든 파일 목록을 가져온다.
		File[] files = dir.listFiles();
		
		// 하위 디렉토리의 인덱스 정보를 저장하기 위한 List 객체 생성
		List<Integer> subDirIndexList = new ArrayList<Integer>();
		
		// 날짜 정보를 출력하기 위한 포맷터 생성
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a hh:mm");
		
		for(int i=0; i<files.length; i++) {
			String attr = ""; // 파일의 속성정보(읽기, 쓰기, 숨김파일, 디렉토리 구분)
			String size = ""; // 파일 크기
			
			if(files[i].isDirectory()) {
				attr = "<DIR>";
				subDirIndexList.add(i); // subDirIndexList의 사이즈는 디렉토리의 갯수
			} else {
				size = files[i].length() + "";
				attr = files[i].canRead() ? "R" : " ";  // 읽을 수 있는지
				attr += files[i].canWrite() ? "W" : " ";  // 쓸 수 있는지
				attr += files[i].isHidden() ? "H" : " ";  // 숨김 파일인지
			}
			
			System.out.printf("%s %5s %12s %s\n", 
								sdf.format(new Date(files[i].lastModified())),
								attr, size, files[i].getName());
		} // for문 끝
		
		int dirCount = subDirIndexList.size(); // 폴더 안의 하위 폴더 개수
		int fileCount = files.length - dirCount; // 폴더 안의 파일 개수
		
		System.out.println(fileCount + " 개의 파일, " + dirCount + " 개의 디렉토리");
		
		System.out.println();
		
		for(int i=0; i<subDirIndexList.size(); i++) {
			// 하위 폴더의 내용들도 출력하기 위해
			// 재귀 호출을 한다.
			displayFileList(files[subDirIndexList.get(i)]);
		}
	}
}

 

결과 화면7 : 재귀 호출을 통해 하위 폴더의 내용들도 출력한다.

 

 

반응형