티스토리 뷰

Development

[Java] 파일 , 폴더 복사

devbible 2011. 8. 31. 15:36

/ **
* ReportLast의 요약 설명입니다.
*/
import java.io.*;

public class ReportLast
{
BufferedReader br;
File source, destination;
String fileSource, fileDestination;

/*
생성자
1. 콘솔입력을 위한 BurreredReader초기화
BufferedReader(Reader in)
2. 메인메뉴 호출
*/

public ReportLast()
{
br = new BufferedReader(new InputStreamReader(System.in));
MainMenu();
}

/*
Input 메소드
인자 : String msg
- msg : 화면에 출력할 문자열(ex 복사대상을 입력하세요...)
- 콘솔입력을 받아, 입력값(String)을 반환
*/
public String Input(String msg)
{
String str = null;
System.out.println(msg);
System.out.print("입력>");
try
{
str = br.readLine();
}
catch (IOException e)
{}
return str.trim();
}

/*
MainMenu() 메소드
- 1) 복사
- 2) 잘라내기
- 3) 종료
*/
public void MainMenu()
{
int index = 0;
String temp = null;
while(true)
{
System.out.println("♨ ===================== ♨");
System.out.println("\t1) 복사");
System.out.println("\t2) 잘라내기");
System.out.println("\t3) 종료");
System.out.println("♨ ===================== ♨");
temp = Input("작업을 선택하세요.");
if(temp.equals("1") || temp.equals("2")) //복사:1, 잘라내기:2
{
파일_폴더처리(Integer.parseInt(temp));
}
else if(temp.equals("3")) //종료
{
System.out.println("시스템을 종료합니다.");
Close(); //br을 닫음.
break;
}
else // 입력값이 잘못된 경우 다시 입력
{
System.out.println("다시입력하세요...");
}
}
}

/*
파일_폴더처리(int copyOrPaste)
인자 : int copyOrPaste : 복사 또는 잘라내기 판단 변수
- filesource와 filedestination을 입력받아 source, destination File 클래스 생성
- source가 파일인 경우 파일복사_잘라내기() 호출
- source가 폴더인 경우 폴더복사_잘라내기() 호출
*/
public void 파일_폴더처리(int copyOrPaste)
{
fileSource = Input("복사대상(경로포함)을 입력하세요..."); //파일 경로를 입력 받음
source = new File(fileSource); //파일 경로를 가지고 File 클래스 생성 File(String Path)
if (source.exists()) // 입력받은 파일(or 폴더)가 존재하는지 판단
{
//파일(or 폴더)가 존재하는 경우
fileDestination = Input("새 이름(경로포함)을 입력하세요..."); //복사할 파일(or폴더)의 경로를 입력받음
destination = new File(fileDestination); //대상 클래스 생성
if(source.isFile())//파일
{
long size = 파일복사_잘라내기(source, destination , true, copyOrPaste); //파일복사_잘라내기()호출
System.out.println("파일 복사( "+size+"byte) 성공");
}
else //폴더
{
long size = 폴더복사_잘라내기(source, destination, copyOrPaste);
System.out.println("성공적으로 복사(총 "+size+"byte)되었습니다."); //폴더복사_잘라내기()호출
}
}
else System.out.println("파일 또는 폴더가 존재하지 않습니다.");
}

/*
파일복사_잘라내기(File sourceFile, File destFile, boolean flag, int copyOrPaste)
인자 : File sourceFile : 원본파일(폴더)
File destFile : 복사할 파일(폴더)
boolean flag : 파일(true) or 폴더내의 파일(false)
폴더인 경우 새로 경로 설정을 하기 위하여 설정
copyOrPaste : 복사(1) or 잘라내기(2)
- sourceFile을 destFile로 복사
- 잘라내기인 경우 파일 삭제
- 파일의 크기 반환
*/
public long 파일복사_잘라내기(File sourceFile, File destFile, boolean flag, int copyOrPaste)
{
String temp = null;
BufferedReader bufR = null;
PrintWriter pw = null;
String tempFileName=null;
try
{
bufR = new BufferedReader(new FileReader(sourceFile)); // 파일을 읽기 위한 BufferedReader 생성

/*
파일을 기록하기 위한 PrintWriter 생성
PrintWriter(Writer out, boolean autoflush)생성자 사용
- 파일인 경우 FileWriter(File file)을 사용하여 FileWriter을 생성
- 폴더인 경우 폴더의 경로를 새로 지정후 FileWriter(String path)를 사용하여 FileWriter을 생성
ex) c:\Test를 c:\Root로 복사할 경우
c:\Test\a.txt는 c:\Root\a.txt로 경로를 설정
*/
if(flag) //파일
pw = new PrintWriter(new FileWriter(destFile), true);
else //폴더
{
//폴더경로 + 파일이름
tempFileName = destFile.getCanonicalPath() + "\\" + sourceFile.getName();
pw = new PrintWriter(new FileWriter(tempFileName), true);
}
temp = null;
while ((temp = bufR.readLine()) != null)
{
pw.println(temp); //파일 읽음
}
}
catch (FileNotFoundException e)
{
System.out.println(sourceFile + "가(이) 존재하지 않습니다.");
return 0;
}
catch (IOException ie) { }
finally
{
try
{
//잘라내기를 할 경우 close해주어야 File.delete() 메소드 사용가능
//close() 하지 않을 경우 File.delete()메소드는 false 반환
if (pw != null)
pw.close();
if (bufR != null)
bufR.close();
}
catch (IOException e)
{ }
}
// 파일의 크기 : 잘라내기인 경우 파일이 삭제 되기전에 파일의 크기를 구해야함...
long size = sourceFile.length();
if (copyOrPaste == 2)
{
sourceFile.delete();
}
return size; // 파일의 크기 반환
}
////////////
/*
폴더복사_잘라내기(File sour, File dest, int copyOrPaste)
인자 : File sour : 원본 폴더
File dest : 복사할 폴더
int copyOrPaste : 복사 or 잘라내기
- 원본폴더의 파일리스트를 가져옴
- 복사할 폴더를 생성
- 원본폴더의 복사할 대상이 파일인 경우 파일복사_잘라내기() 호출
- 원본폴더의 복사할 대상이 폴더인 경우 폴더복사_잘라내기()를 재귀호출
- 총 폴더 크기 반환
*/
public long 폴더복사_잘라내기(File sour, File dest, int copyOrPaste)
{
long sum = 0l;
dest.mkdir(); //복사할 폴더를 생성
File[] files = sour.listFiles(); // 원본 폴더의 파일리스트를 가져옴
for (int i = 0; i < files.length; i++)
{
if (files[i].isFile()) //폴더내의 파일인 경우
{
//파일복사_잘라내기에 파일리스트의 객체를 전달
sum += 파일복사_잘라내기(files[i] , dest, false, copyOrPaste);
}
else //하위 디렉토리
{
try
{
//원본 폴더내의 파일을 복사하기 위하여 복사할 폴더의 파일경로 설정
String subDestPath = dest.getCanonicalPath() + "\\" + files[i].getName();
File subDest = new File(subDestPath);
//하위 폴더를 처리하기 위한 재귀 호출
sum += 폴더복사_잘라내기(files[i], subDest,copyOrPaste);
//잘라내기 일경우 하위 폴더 삭제
if(copyOrPaste == 2)
files[i].delete();
}
catch (IOException e)
{}
}
}
//잘라내기인 경우 원본폴더 삭제
if(copyOrPaste == 2)
sour.delete();
return sum;
}

//BufferedReader를 닫음
public void Close()
{
if(br != null)
{
try
{
br.close();
System.out.println("시스템 종료");
}
catch (IOException e)
{
System.out.println("비정상 종료");
}
}
}
public static void main(String args[])
{
new ReportLast();

}
}






[저작자] 김은실 (에리카)
[원본및 출처] http://cafe.naver.com/sungwookhome.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=76
댓글