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

최근 두가지 글을 포스팅했습니다.

 

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

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

 

위의 두가지 글이 바로 최근 포스팅했던 글들인데요. 자바로 폴더 및 파일을 이동시키는 방법은 위에 있는 두개의 포스팅을 합치면 구현하실 수 있습니다. 

 

자바로 폴더(디렉토리),파일 이동시키기

1. 폴더 및 파일을 복사한다.

2. 복사했던 폴더 및 파일을 삭제시킨다.


  
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Move {
public static void main(String[] args) {
File folder1 = new File("D:\\Eclipse\\Java\\이동할폴더");
File folder2 = new File("D:\\Eclipse\\Java\\이동된폴더");
Move.copy(folder1, folder2);
Move.delete(folder1.toString());
}
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();
}
}
}
}
}
public static void delete(String path) {
File folder = new File(path);
try {
if(folder.exists()){
File[] folder_list = folder.listFiles();
for (int i = 0; i < folder_list.length; i++) {
if(folder_list[i].isFile()) {
folder_list[i].delete();
}else {
delete(folder_list[i].getPath());
}
folder_list[i].delete();
}
}
} catch (Exception e) {
e.getStackTrace();
}
}
}

이동할폴더
이동된폴더
이동후삭제

 

코딩팩토리님의
글이 좋았다면 응원을 보내주세요!

Designed by JB FACTORY