본문 바로가기

Program/Java Core

[Java] 재귀함수를 이용한 폴더 복사

pSourcePath: 소스 디렉토리 경로, pDestinationPath: 목적 디렉토리 경로, pOverWrite: 덮어쓰기 유무

public void copyDirectory(String pSourcePath, String pDestinationPath, Boolean pOverWrite) throws IOException {

File sourceDir = new File(pSourcePath);

File destinationDir = new File(pDestinationPath);

String[] sourceDirFiles;


if (sourceDir.isDirectory() && sourceDir.exists()) {

sourceDirFiles = sourceDir.list();


if (!destinationDir.exists()) {

destinationDir.mkdir();

}


for (int i = 0; i < sourceDirFiles.length; i++) {

String sourceDirPath = pSourcePath + File.separatorChar + sourceDirFiles[i];

String destinationDirPath = pDestinationPath + File.separatorChar + sourceDirFiles[i];


File sFile = new File(sourceDirPath);

File dFile = new File(destinationDirPath);


if (sFile.isDirectory()) {

copyDirectory(sourceDirPath, destinationDirPath, pOverWrite);

} else {

byte[] fileBuf = new byte[1024];

int bufLength;


if (pOverWrite) {

InputStream in = new FileInputStream(sFile);

OutputStream out = new FileOutputStream(dFile);


while ((bufLength = in.read(fileBuf)) > 0) {

out.write(fileBuf, 0, bufLength);

}


in.close();

out.close();

} else if (!pOverWrite && !dFile.exists()) {

InputStream in = new FileInputStream(sFile);

OutputStream out = new FileOutputStream(dFile);


while ((bufLength = in.read(fileBuf)) > 0) {

out.write(fileBuf, 0, bufLength);

}


in.close();

out.close();

}

}

}

}

}