Jun's Blog

[Java] File 활용한 예제 본문

High Java/IO

[Java] File 활용한 예제

Fizzyelf 2020. 10. 22. 20:26
package kr.or.ddit.basic;

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

public class T01_FileTest {
	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:/D_Other", "test.txt");
		File file4 = new File("../././././test.txt");
		System.out.println("절대 경로 : " + file4.getAbsolutePath());	// 언제쓰면좋을까? 자주 변하지 않는 경로.
		System.out.println("경로 : " + file4.getPath());	//생성자에 넣어준 경로
		System.out.println("표준 경로 : " + file4.getCanonicalPath());
		System.out.println("현재 클래스의 URL : " + T01_FileTest.class.getResource("T01_FileTest.class").getPath());
	
	/**
	 * 디렉토리(폴더) 만들기
	 * 
	 * 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() + " 만들기 실패!");
		}
		System.out.println();

		File file6 = new File("d:/D_Other/test/java/src");

		if (file6.mkdir()) {
			System.out.println(file6.getName() + " 만들기 성공!");
		} else {
			System.out.println(file6.getName() + " 만들기 실패!");
		}
		System.out.println();
	}
}

package kr.or.ddit.basic;

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

public class T02_FileTest {
	public static void main(String[] args) {
		
		File f1 = new File("d:/D_Other/smaple.txt");
		File f2 = new File("d:/D_Other/test.txt");
		
		if(f1.exists()) {
			System.out.println(f1.getAbsolutePath() + "은 존재합니다.");
		} else {
			System.out.println(f1.getAbsolutePath() + "은 없는 파일입니다.");
			
			try {
				if(f1.createNewFile()) {
					System.out.println(f1.getAbsolutePath() + "파일을 새로 만들었습니다.");
				}
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
		
		if(f2.exists()) {
			System.out.println(f2.getAbsolutePath() + "은 존재합니다");
		} else {
			System.out.println(f2.getAbsolutePath() + "은 없는 파일입니다");
		}
		System.out.println("-------------------------------------");
		
		File f3 = new File("d:/D_Other");
		File[] files = f3.listFiles();
		for(File file : files) {
			System.out.print(file.getName() + " => ");
			if(file.isFile()) {
				System.out.println("파일");
			} else if(file.isDirectory()) {
				System.out.println("디렉토리");
			}
		}
		System.out.println("-------------------------------------");
		
		String[] strFiles = f3.list();
		for(String file : strFiles) {
			System.out.println(file);
		}
		System.out.println("-------------------------------------");
		System.out.println();
		
		//===========================================================================
		
		// 출력할 때 디렉토리 정보를 갖는 File객체 생성
		File f4 = new File("D:\\A_TeachingMaterial");
		
		displayFileList(f4);	// 메서드  호출
	}

	// 지정된 디렉토리(폴더)에 포함된 파일과 디렉토리 목록을 보여주는 메서드
	private static void displayFileList(File dir) {
		System.out.println("[" + dir.getAbsolutePath() + "] 디렉토리 내용");
		
		// 디렉토리 안의 모든 파일 목록을 가져온다.
		File[] files = dir.listFiles();
		
		// 하위 디렉토리 정보를 저장할 ArrayList 생성(File 배열의 인덱스 저장)
		List<Integer> subDirList = 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>";
				subDirList.add(i);
			} 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"		// 5s  사이즈를 5개로 끊는다
					,sdf.format(new Date(files[i].lastModified()))
					,attr, size, files[i].getName());
			
		}
		
		int dirCount = subDirList.size(); // 폴더만의 하위폴더 개수 구하기
		int fileCount = files.length - dirCount; // 폴더안의 파일 개수 구하기
		
		System.out.println(fileCount + "개의 파일, " + dirCount + "개의 디렉토리");
		System.out.println();
		
		for(int i=0; i < subDirList.size(); i++) {
			// 하위폴더의 내용들도 출력하기 위해 현재 메서드를 재귀호출하여 처리한다.
			displayFileList(files[subDirList.get(i)]);
		}
	}
}

'High Java > IO' 카테고리의 다른 글

[Java] FileStream 파일 읽기&출력 예제  (0) 2020.10.23
[Java] byteArrayIO 예제  (0) 2020.10.23
Comments