In this section we will be showing how to copy a folder in java. This means we need to have a recursive ways to copy a file. The java.io package contains FileInputStream and FileOutputStream classes providing methods to read a source file and then write the contents source target file. However this is only true for a single file. This source code shows how to do this recursively.
Copy to copy a folder in Java
This source code does not only shows how to copy multiple files but also checks target folder to be existing or not. Moreover it also creates a directory tree to satisfy the copy functionality requirements. The copy folder functionality is put in a method for ease of use if you decide to have this extend or imported as a library in your own java implementation. There were two methods exposed on this example, one is copyFile and copyDirectory. If you are just copying a single file, you can use the CopyFile method. However if you need a copy folder functionality please use the copyDirectory method.
package com.javatutorialhq.tutorial;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFileRecursiveIO {
/**
* This sample code shows how copy a folder in java
* illustrating recursive file copy
* Property of javatutorialhq.com
* All Rights Reserved
* Version 1.0
* 06/21/2012
*/
private static File fileInput = new File("C:\\temp\\sourcefolder");
private static File fileOutput = new File("C:\\temp\\targetfolder");
public static void main(String[] args) throws IOException {
CopyFileRecursiveIO testObject = new CopyFileRecursiveIO();
System.out.println("Executing Java recursive Folder Copy");
System.out.println("Success:"
+ testObject.CopyDirectory(fileInput, fileOutput));
}
// copy Directory method
public boolean CopyDirectory(File source, File target) throws IOException {
// check first if source file exists or not
if (!source.exists()) {
return false;
}
if (source.isDirectory()) {
if (!target.exists()) {
target.mkdir();
}
File[] listFile = source.listFiles();
for (File f : listFile) {
File sourceFile = new File(source, f.getName());
File outputFile = new File(target, f.getName());
if (f.isDirectory()) {
new CopyFileRecursiveIO().CopyDirectory(sourceFile,
outputFile);
} else {
new CopyFileRecursiveIO().copyFile(sourceFile, outputFile);
}
}
}
return true;
}
// Copy file method
public void copyFile(File input, File output) throws IOException {
FileInputStream inputStream = new FileInputStream(input);
// target file declaration
FileOutputStream outputStream = new FileOutputStream(output);
int lengthStream;
byte[] buff = new byte[1024];
while ((lengthStream = inputStream.read(buff)) > 0) {
// writing to the target file contents of the source file
outputStream.write(buff, 0, lengthStream);
}
outputStream.close();
inputStream.close();
}
}
Sample Output:
Executing Java recursive Folder Copy Success:true