반응형

문제

문제 13을 확장하여 다음 명령을 추가하라.

 

명령 사용 예시

>>rename phone txt p.txt //phone.txt를 p.txt로 변경. 파일과 디렉터리 이름 변경
>>mkdir xxx // 현재 디렉터리 밑에 xxx 디렉터리 생성

 

소스 코드 ( 실습문제 13번 디렉터리 이동 부분 NullPointerException 오류도 수정 하였습니다. )

import java.io.*;
import java.util.*;

public class Main13 {
	public static void ListFile(File f) {
		File[]subFiles = f.listFiles();
		for(int i = 0;i<subFiles.length;i++) {
			File file = subFiles[i];
			
			// 파일 종류
			if(file.isDirectory())
				System.out.print("dir\t");
			else if(file.isFile())
				System.out.print("file\t");
			
			System.out.printf(file.length()+"바이트"); // 파일 크기
			System.out.println("   \t"+file.getName()); // 파일이름
		}
	}
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		File f = new File("C:\\");
		Scanner s = new Scanner(System.in);
		System.out.println("***** 파일 탐색기입니다. *****");
		System.out.println("\t["+f.getPath()+"]");
		ListFile(f);
		while(true) {
			
			System.out.print(">>");
			String search = s.next();
			if(search.equals("그만")) {
				break;
			}
			else if(search.equals("..")) {
				File temp = new File(f.getParent());
				f = temp;
			}
			else if(search.equals("rename")) {
				String Changename = s.nextLine();
				try {
					StringTokenizer st = new StringTokenizer(Changename," ");
					while(st.hasMoreTokens())
					{
						File temp = new File(f.getPath()+"\\"+st.nextToken());
						File renameFile = new File(f.getPath()+"\\"+st.nextToken());
						temp.renameTo(renameFile);
					}
				}catch(NoSuchElementException e) {
					System.out.println("두 개의 파일명이 주어지지 않았습니다.!");
					continue;
				}
			}
			
			else if(search.equals("mkdir")) {
				String name = s.nextLine();
				File fout = new File(f.getPath()+"\\"+name);
				if(!fout.exists()) {
					System.out.println(fout.getName()+ " 디렉터리를 생성하였습니다.");
					fout.mkdir();
				}
				else {
					System.out.println("이미 존재하는 파일입니다.");
					continue;
				}
				
			}
			else {
					File temp = new File(f.getPath()+"\\"+search);	
					f = temp;		
			}
			try {
				System.out.println("\t["+f.getPath()+"]");
				ListFile(f);
			}catch(NullPointerException e) {
				System.out.println("없는 파일입니다.");
				continue;
			}
		}
		s.close();
	}
}
반응형

+ Recent posts