프로그래밍&IT/java
[Java 자바] 디렉토리/파일 복사
sjoo
2022. 9. 2. 14:23
자바 File클래스에 listFiles() 메서드를 사용하여 모든 파일 정보를 가져와 다른 디렉토리에 복사하려고 한다.
재귀적으로 호출하여 하위 디렉토리부터 상위폴더로 올라가면서 파일을 복사하여 특정 경로에 폴더에 모든 파일을 복사하여 지정 경로에 파일을 복사하려고 한다.
[사용방법]
copyDir(File sourceF, File targetF);
public void copyDir(File sourceF, File targetF){
File[] target = sourceF.listFiles();
for (File file : target) {
File temp = new File(targetF.getAbsolutePath() + File.separator + file.getName());
if(file.isDirectory()){
temp.mkdir();
copyDir(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) {
LOGGER.error("{}", e);
}
}
}
}
}
[참고]
[Java] 자바로 폴더(디렉토리),파일 복사하기 (tistory.com)
[Java] 자바로 폴더(디렉토리),파일 복사하기
자바 File클래스에는 폴더에있는 모든 파일정보를 가지고 오는 메서드인 listFiles()라는 메서드가 존재합니다. 이 listFiles() 메서드와 File클래스의 파일생성 메서드인 mkdir()를 활용하면 쉽게 파일을
coding-factory.tistory.com