[Java] 자바로 폴더(디렉토리),파일 복사하기

자바 File클래스에는 폴더에있는 모든 파일정보를 가지고 오는 메서드인 listFiles()라는 메서드가 존재합니다. 이 listFiles() 메서드와 File클래스의 파일생성 메서드인 mkdir()를 활용하면 쉽게 파일을 복사하실 수 있습니다.

 

자바로 파일 복사하기

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Copy{
	
    public static void main(String[] args) {
	File folder1 = new File("D:\\Eclipse\\Java\\복사할폴더\\복사될폴더");
	File folder2 = new File("D:\\Eclipse\\Java\\복사된폴더");
		
	File[] target_file = folder1.listFiles();
	for (File file : target_file) {
		File temp = new File(folder2.getAbsolutePath() + File.separator + file.getName());
		if(file.isDirectory()){
			temp.mkdir();
		} else {
			FileInputStream fis = null;
			FileOutputStream fos = null;
			try {
				fis = new FileInputStream(file);
				fos = new FileOutputStream(temp) ;
				byte[] b = new byte[4096];
				int cnt = 0;
				while((cnt=fis.read(b)) != -1){
					fos.write(b, 0, cnt);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				try {
					fis.close();
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					
			}
		}
	}
    }
}

하지만 위와 같은 방법으로 단순하게 복사 대상의 정보만 읽어와서 디렉토리 복사를 진행할경우. 엄청난 결함이생깁니다. 복사대상 폴더 내부에 파일만 있을경우에는 문제가 없겠지만 폴더가 있고 그 폴더안에 파일이 또 있을경우에는 더 내부의 파일은 복사가 되지않고 껍데기만 복사가 됩니다. 

복사된폴더
복사안됨

이 문제를 해결하기 위해서는 복사 대상폴더의 내부 폴더를 일일이 들어가 재귀적으로 호출하여 가장 하위 디렉토리부터 파일을 복사해준뒤 한단계 한단계 상위폴더로 올라가는 작업을 해주어야합니다.

 

재귀함수를 활용하여 최하위 폴더부터 차례대로 복사하기

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Copy {
	
    public static void main(String[] args) {
	File folder1 = new File("D:\\Eclipse\\Java\\복사할폴더\\복사될폴더");
	File folder2 = new File("D:\\Eclipse\\Java\\복사된폴더");
	Copy.copy(folder1, folder2);
    }
	
    public static void copy(File sourceF, File targetF){
	File[] target_file = sourceF.listFiles();
	for (File file : target_file) {
		File temp = new File(targetF.getAbsolutePath() + File.separator + file.getName());
		if(file.isDirectory()){
			temp.mkdir();
			copy(file, temp);
		} else {
			FileInputStream fis = null;
			FileOutputStream fos = null;
			try {
				fis = new FileInputStream(file);
				fos = new FileOutputStream(temp) ;
				byte[] b = new byte[4096];
				int cnt = 0;
				while((cnt=fis.read(b)) != -1){
					fos.write(b, 0, cnt);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				try {
					fis.close();
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
		}
	  }	
    }
}

복사된폴더

 

복사됨

 

[Java] 자바로 폴더(디렉토리) 생성하기

[Java] 자바로 폴더(디렉토리) 삭제하기(하위파일, 폴더 포함)

[Java] 자바로 폴더(디렉토리),파일 이동시키기 / 잘라내기

 

댓글

Designed by JB FACTORY