- Java Copy Directory Examples
- 1. Use Java IO To Copy Directory.
- 2. Use Apache Commons IO.
- 3. Use Java New IO.
- 4. Difference Between Java IO and Apache Commons IO.
- How to copy a resource directory and all included files and sub-folders in a Jar onto another directory
- How to copy a resource directory and all included files and sub-folders in a Jar onto another directory
- How to copy the directory content using recursive copy in Java?
- Java — Moving all sub-directory files to Parent Directory
- Copy directory files into subfolder
- Copy directory ,sub directories and files to sd card
- Copy a directory with files and subdirectories in Java
- 2. Copy directory using Java 7
- 3. Copy directory using java.io API (recursion)
- 4. Copy directory using Apache Commons IO library
- 5. Conclusion
Java Copy Directory Examples
Today I will show you three java examples that copy the source directory with it’s content to the target directory.
1. Use Java IO To Copy Directory.
- This example uses the traditional java File and Input / Output Stream class to implement the copy directory process. You can see code comments for more detail.
public void copyDirectory(String srcDir, String destDir) < try < // Create source object. File srcDirFile = new File(srcDir); // Create destination object. File destDirFile = new File(destDir); /* Only copy exist directory. */ if(srcDirFile.exists()) < if(srcDirFile.isDirectory()) < /* If destination directory is not exist then create it. */ if(!destDirFile.exists()) < destDirFile.mkdirs(); System.out.println("Target Directory " + destDirFile + " dose not exist, create it."); >/* Get source directory sub-content. */ File[] srcDirSubFileArr = srcDirFile.listFiles(); /* Loop in the directory sub content. */ for(File srcDirSubFile : srcDirSubFileArr) < /* Get subfile name. */ String subFileName = srcDirSubFile.getName(); /* Create source subfile and target subfile. */ File subSrcFile = new File(srcDirFile, subFileName); File subDestFile = new File(destDirFile, subFileName); /* Copy recursively. */ copyDirectory(subSrcFile.getCanonicalPath(), subDestFile.getCanonicalPath()); System.out.println("Recursive copy from " + subSrcFile.getCanonicalPath() + " to " + subDestFile.getCanonicalPath()); >>else < /* If source is a file. */ this.copyFile(srcDirFile, destDirFile); >> >catch(Exception ex) < ex.printStackTrace(); >> /* Copy data from source to target. * */ public void copyFile(File srcFile, File destFile) throws IOException < /* Create buffered input stream to improve read speed. */ InputStream srcInput = new FileInputStream(srcFile); BufferedInputStream srcBis = new BufferedInputStream(srcInput); /* Create buffered output stream to improve write speed. */ OutputStream destOutput = new FileOutputStream(destFile); BufferedOutputStream destBos = new BufferedOutputStream(destOutput); byte byteBufferArr[] = new byte[1024]; /* Read byte data to buffer, if all data has been read then readLen==-1. */ int readLen = srcBis.read(byteBufferArr); while(readLen>0) < destBos.write(byteBufferArr); readLen = srcBis.read(byteBufferArr); >/* Do not forget flush output stream buffer and close both input and output buffer stream.*/ destBos.flush(); destBos.close(); destOutput.close(); srcBis.close(); srcInput.close(); System.out.println("Copy successful from " + srcFile.getCanonicalPath() + " to " + destFile.getCanonicalPath()); >
2. Use Apache Commons IO.
- Go to Apache commons-io download page.
- Download the latest version.
- After download, extract the zip file to a local folder. Then add commons-io-2.5.jar to your java project as below. You can read How to add selenium server standalone jar into your java project to learn how to add a jar in the java project.
- Java example code.
/* Use Apache commons io to copy directory. * srcDirPath : Source folder path. * destDirPath : Target folder path. * fileExtension : If empty then copy all, if specified then only copy those extension file, such as "exe", "txt" etc. * */ public void copyWithApacheCommonsIO(String srcDirPath, String destDirPath, String fileExtension) < try < File srcDir = new File(srcDirPath); File destDir = new File(destDirPath); if("".equals(fileExtension)) < /* Copy all. */ /* Will create destDir automatically if destDir dose not exist. */ FileUtils.copyDirectory(srcDir, destDir); >else < /* Copy special extension file. */ /* Create a special extension filter.*/ IOFileFilter fileExtensionFilter = FileFilterUtils.suffixFileFilter(fileExtension); /* Use and(IOFileFilter . fileFilter) method to declare a filter that only copy those extension file, such as "exe", "txt". * The and method three-dot means the method parameter can be zero or more IOFileFilter object, or a IOFileFilter array. * */ IOFileFilter fileFilter = FileFilterUtils.and(FileFileFilter.FILE, fileExtensionFilter); /* Use or(IOFileFilter . fileFilter) method to tell FileUtils copy either directory or specified extension file just created. */ FileFilter fileAndDirFilter = FileFilterUtils.or(DirectoryFileFilter.DIRECTORY, fileFilter); // Copy using the filter FileUtils.copyDirectory(srcDir, destDir, fileAndDirFilter); >System.out.println(srcDirPath + " has been copied to " + destDirPath + " successfully. "); >catch(Exception ex) < ex.printStackTrace(); >>
3. Use Java New IO.
- Create a File visitor class first, this visitor will be invoked during java new io’s Files.walkFileTree() method. The below file JavaNewIOCopyFileVisitor.java is an example.
public class JavaNewIOCopyFileVisitor extends SimpleFileVisitor < private String srcDir; private String destDir; public String getSrcDir() < return srcDir; >public void setSrcDir(String srcDir) < this.srcDir = srcDir; >public String getDestDir() < return destDir; >public void setDestDir(String destDir) < this.destDir = destDir; >@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes arg1) throws IOException < /* Get both source and destination directory Path object. */ Path srcPath = Paths.get(this.getSrcDir()); Path destPath = Paths.get(this.getDestDir()); /* Get the relative Path object between source and current directory. */ Path relativePath = srcPath.relativize(dir); /* Get the target directory Path instance. */ Path targetDirPath = destPath.resolve(relativePath); try < /* Copy current go through directory to target directory, replace target if exist. */ Files.copy(dir, targetDirPath, StandardCopyOption.REPLACE_EXISTING); >catch (FileAlreadyExistsException ex) < if (!Files.isDirectory(targetDirPath)) throw ex; >return FileVisitResult.CONTINUE; > @Override public FileVisitResult visitFile(Path file, BasicFileAttributes arg1) throws IOException < /* Get both source and destination directory Path object. */ Path srcPath = Paths.get(this.getSrcDir()); Path destPath = Paths.get(this.getDestDir()); /* Get Path object that current file relative to source folder. */ Path relativeFilePath = srcPath.relativize(file); /* Use the relative path to get target folder Path object. */ Path targetFilePath = destPath.resolve(relativeFilePath); /* Copy current file to target file, replace target if exist. */ Files.copy(file, targetFilePath, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; >>
/* Copy source directory to target directory use java new io. */ public void copyWithJavaNewIO(String srcDir, String destDir) < try < /* First create a file visitor object which will be invoked when go through each file or directory. */ JavaNewIOCopyFileVisitor copyFileVisitor = new JavaNewIOCopyFileVisitor(); copyFileVisitor.setSrcDir(srcDir); copyFileVisitor.setDestDir(destDir); /* Create the root copy Path object. */ Path srcPath = Paths.get(srcDir); /* Walk through each file or directory under the root path.*/ Files.walkFileTree(srcPath, copyFileVisitor); System.out.println(srcDir + " has been copied to " + destDir + " successfully. "); >catch(Exception ex) < ex.printStackTrace(); >>
4. Difference Between Java IO and Apache Commons IO.
- Apache Commons IO provides more useful classes with advanced features.
- Apache Commons IO and Java IO copy speed are not too much different.
- Below is the java main method, we have record the two copy methods used time. The source directory is about 4 Gigabyte, we can see two methods used time is nearly the same.
public static void main(String[] args) < CopyDirectoryExample cde = new CopyDirectoryExample(); /* Below code will copy only .exe file from source to target folder. */ cde.copyWithApacheCommonsIO("C:/WorkSpace/DreamWeaver", "C:/WorkSpace/DreamWeaver_bak", "exe"); long startTime = 0; long endTime = 0; startTime = System.currentTimeMillis(); cde.copyDirectory("C:/WorkSpace/dev2qa.com", "C:/WorkSpace/dev2qa.com_bak_1"); endTime = System.currentTimeMillis(); long deltaTime = endTime - startTime; System.out.println("copyDirectory(String srcDir, String destDir) use time " + deltaTime); startTime = System.currentTimeMillis(); cde.copyWithApacheCommonsIO("C:/WorkSpace/dev2qa.com", "C:/WorkSpace/dev2qa.com_bak_2", ""); endTime = System.currentTimeMillis(); deltaTime = endTime - startTime; System.out.println("copyWithApacheCommonsIO(String srcDir, String destDir) use time " + deltaTime); startTime = System.currentTimeMillis(); cde.copyWithJavaNewIO("C:/WorkSpace/dev2qa.com", "C:/WorkSpace/dev2qa.com_bak_nio"); endTime = System.currentTimeMillis(); deltaTime = endTime - startTime; System.out.println("copyWithJavaNewIO(String srcDir, String destDir) use time " + deltaTime); >
Recursive copy from C:\WorkSpace\dev2qa.com\Zhao Song English_Resume.doc to C:\WorkSpace\dev2.com\Zhao Song English_Resume_1.doc copyDirectory(String srcDir, String destDir) use time 396303 C:\WorkSpace\dev2qa.com has been copiea to C:\WorkSpace\dev2qa.com_bak_2 successfully. copyWithApacheCommonsIO(String srcDir, String destDir) use time 390880
How to copy a resource directory and all included files and sub-folders in a Jar onto another directory
Question: I am trying to move all files I have stored in a sub-directories to the parent directory they all belong to. Question: Is it possible to copy a resource folder, and all the files within, including all directories and sub directories therein into another directory?
How to copy a resource directory and all included files and sub-folders in a Jar onto another directory
Is it possible to copy a resource folder, and all the files within, including all directories and sub directories therein into another directory?
What I’ve managed so far is to copy only one file resource, which is a CSS file:
public void addCSS() < Bundle bundle = FrameworkUtil.getBundle(this.getClass()); Bundle[] bArray = bundle.getBundleContext().getBundles(); Bundle cssBundle = null; for (Bundle b : bArray) < if (b.getSymbolicName().equals("mainscreen")) < cssBundle = b; break; >> Enumeration resources = null; try < resources = cssBundle.getResources("/resources/css/mainscreen.css"); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >if (resources != null) < URL myCSSURL = resources.nextElement(); InputStream in; try < in = myCSSURL.openStream(); File css = new File(this.baseDir() + "/ui/resources/css/mainscreen.css"); try (FileOutputStream out = new FileOutputStream(css)) < IOUtils.copy(in, out); >> catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> >
You need Bundle.findEntries(path,mask,recurse) . This method was designed for this purpose, works beautifully with fragments as well.
void getCSSResources( List out ) for ( Bundle b : context.getBundles() < Enumeratione = b.findEntries("myapp/resources", "*.css", true); while (e.hasMoreElements() < out.add(e.nextElement()); >> >
How to move files from Parent directory to subdirectory in java?, You can use Files.walk to create a stream of Path instances, filter the files and copy them to the destination. try(Stream
How to copy the directory content using recursive copy in Java?
Java Source Code here:http://ramj2ee.blogspot.com/2016/11/java-tutorial-java-io-java-file Duration: 2:26
Java — Moving all sub-directory files to Parent Directory
I am trying to move all files I have stored in a sub-directories to the parent directory they all belong to.
I am aware that this can be done through a shell script which could possibly be run through Java but was hoping for a method which could be done using Java by itself.
I’m initially using code from here: https://stackoverflow.com/a/26214647/5547474 to copy all files but it doesn’t do everything I require.
Any help would be much appreciated, thanks!
private static void move(File toDir, File currDir) < for (File file : currDir.listFiles()) < if (file.isDirectory()) < move(toDir, file); >else < file.renameTo(new File(toDir, file.getName())); >> >
Usage: pass it parent directory (ex. move(parentDir, parentDir)).
How to copy an entire content from a directory to another in Java?, Would recommend using FileUtils in Apache Commons IO: FileUtils.copyDirectory(new File(«C:/FilesToGo/»), new File(«C:/Kingdoms/»));.
Copy directory files into subfolder
i want to copy files from parent directory into subfolder in parent directory. Now i get the copied files into subfolder, but it repeated itself everytime if i get already the subfolder and files copied, it makes it all time repeatedly, i want it to male only one time
public static void main(String[] args) throws IOException < File source = new File(path2); File target = new File("Test/subfolder"); copyDirectory(source, target); >public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException < if (sourceLocation.isDirectory()) < if (!targetLocation.exists()) < targetLocation.mkdir(); >String[] children = sourceLocation.list(); for (int i = 0; i < children.length; i++) < copyDirectory(new File(sourceLocation, children[i]), new File( targetLocation, children[i])); >> else < InputStream in = new FileInputStream(sourceLocation); OutputStream out = new FileOutputStream(targetLocation); byte[] buf = new byte[1]; int length; while ((length = in.read(buf)) >0) < out.write(buf, 0, length); >in.close(); out.close(); > >
You program have problem in following line
String[] children = sourceLocation.list();
Lets suppose your parent dir = Test So the following code will create a sub-folder under test
And after that you are retrieving the children of source folder as your destination is already created it will also be counted as child of source folder and recursively get copied. So you need to retrieve children first and then create the target directory So that target directory would not be count in copy process. Change your code as follows.
public static void main(String[] args) throws IOException < File source = new File("Test"); File target = new File("Test/subfolder"); copyDirectory(source, target); >public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException < String[] children = sourceLocation.list(); if (sourceLocation.isDirectory()) < if (!targetLocation.exists()) < targetLocation.mkdir(); >for (int i = 0; i < children.length; i++) < copyDirectory(new File(sourceLocation, children[i]), new File( targetLocation, children[i])); >> else < InputStream in = new FileInputStream(sourceLocation); OutputStream out = new FileOutputStream(targetLocation); byte[] buf = new byte[1]; int length; while ((length = in.read(buf)) >0) < out.write(buf, 0, length); >in.close(); out.close(); > >
You are calling your method recursively without a condition to break the recursion. You will have to exclude directories in your for-loop.
Moving a file from one directory to another using Java, Java provides functions to move files between directories. Two ways to achieve this are described here. The first method utilizes Files
Copy directory ,sub directories and files to sd card
I use the following code to copy a particular directory and its contents to the sd card. The directory is placed inside res/raw folder.
Following is the code I use:
public class CopyActivity extends Activity < /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); copyFilesToSdCard(); >static String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); final static String TARGET_BASE_PATH = extStorageDirectory+"/Android/data/"; private void copyFilesToSdCard() < copyFileOrDir(""); >private void copyFileOrDir(String path) < AssetManager assetManager = this.getAssets(); String assets[] = null; try < Log.i("tag", "copyFileOrDir() "+path); assets = assetManager.list(path); if (assets.length == 0) < copyFile(path); >else < String fullPath = TARGET_BASE_PATH + path; Log.i("tag", "path="+fullPath); File dir = new File(fullPath); if (!dir.exists()) if (!dir.mkdirs()); Log.i("tag", "could not create dir "+fullPath); for (int i = 0; i < assets.length; ++i) < String p; if (path.equals("")) p = ""; else p = path + "/"; copyFileOrDir( p + assets[i]); >> > catch (IOException ex) < Log.e("tag", "I/O Exception", ex); >> private void copyFile(String filename) < AssetManager assetManager = this.getAssets(); InputStream in = null; OutputStream out = null; String newFileName = null; try < Log.i("tag", "copyFile() "+filename); in = assetManager.open(filename); if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4); else newFileName = TARGET_BASE_PATH + filename; out = new FileOutputStream(newFileName); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) < out.write(buffer, 0, read); >in.close(); in = null; out.flush(); out.close(); out = null; > catch (Exception e) < Log.e("tag", "Exception in copyFile() of "+newFileName); Log.e("tag", "Exception in copyFile() "+e.toString()); >> >
Exception in copyFile() of /mnt/sdcard/Android/data/raw/edu/anees.txt Exception in copyFile() java.io.FileNotFoundException: /mnt/sdcard/Android/data/raw/edu/anees.txt: open failed: ENOENT (No such file or directory)
Can someone please let me know what causes this issue and solution for the same.
ref: How to copy files from ‘assets’ folder to sdcard?
I could resolve the exception with one of the tips regarding permission which was posted as one answer here.
Now I encounter another issue which is as follows:
The following log says I cannot create a folder in the following path:
Log.i("tag", "could not create dir "+fullPath);// fullPath = /mnt/sdcard/Android/data/raw
I do not want to have the data stored inside /mnt/sdcard/Android/data/raw, but instead, I want to have the contents of the raw folder inside assets to be copied to the path /mnt/sdcard/Android/data which is not happening with the piece of code I use from the reference link I gave. Any obvious reasons that might cause this with the code I gave?
You might have forgotten to set the permission in your manifest
Copy files from a folder and Paste to another directory sub-folders in, I was stuck on pasting credits files to all subdirectories, so first, I checked all the dir via listdir, and implements for loop for both
Copy a directory with files and subdirectories in Java
In this article, we will present how to copy a directory in Java with all files and subdirectories. We are going to use plain Java and external library Apache Commons IO.
2. Copy directory using Java 7
Let’s start with the approach available in plain Java using IO libraries.
Java from version 7 provided Paths and many useful features to manipulate files and directories.
package com.frontbackend.java.io.copy; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CopyDirectoryUsingWalk < public static void main(String[] args) throws IOException < final Path fromPath = Paths.get("/tmp/from"); Files.walk(fromPath) .forEach(source ->copySourceToDest(fromPath, source)); > private static void copySourceToDest(Path fromPath, Path source) < Path destination = Paths.get("/tmp/to", source.toString() .substring(fromPath.toString() .length())); try < Files.copy(source, destination); >catch (IOException e) < e.printStackTrace(); >> >
In this example, we used the Files.walk(. ) method available in java.nio package. We walked through the file tree starting from the root — source directory. Then we used Files.copy(. ) to copy files and directories that we found on the way.
Assume we have the following folder structure:
├── from │ ├── dir │ │ └── third │ ├── first │ └── second
After running our first example code the new directory will appear in /tmp directory with the following files and subdirectories:
└── to ├── dir │ └── third ├── first └── second
3. Copy directory using java.io API (recursion)
In older java.io API we don’t have a dedicated method to walk through a directory tree, so we need to use recursion to list files with directories and subdirectories.
Let’s check out this approach:
package com.frontbackend.java.io.copy; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyDirectoryUsingRecursion < public static void main(String[] args) throws IOException < File sourceDir = new File("/tmp/from"); File destDir = new File("/tmp/to"); copyDirectory(sourceDir, destDir); >private static void copyDirectory(File sourceDir, File destDir) throws IOException < if (!destDir.exists()) < destDir.mkdir(); >for (String f : sourceDir.list()) < File source = new File(sourceDir, f); File destination = new File(destDir, f); if (source.isDirectory()) < copyDirectory(source, destination); >else < copyFile(source, destination); >> > private static void copyFile(File sourceFile, File destinationFile) throws IOException < FileInputStream input = new FileInputStream(sourceFile); FileOutputStream output = new FileOutputStream(destinationFile); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buf)) >0) < output.write(buf, 0, bytesRead); >input.close(); output.close(); > >
In this example, we implemented two methods: copyDirectory and copyFile . The first method will be called recursively for every folder we found in the tree. We started with the root source and destination folders and run copyDirectory(sourceDir, destDir) method.
In copyDirectory(. ) method we list all resources and check is it a file or directory. If the resource is a directory we called again copyDirectory(. ) method. In case we found a file we use copyFile(. ) to copy file from one path to another.
4. Copy directory using Apache Commons IO library
The Apache Commons IO library comes with many utility classes and methods for manipulating files.
In the following example we used FileUtils class that provide methods for reading, writing, and copying files:
package com.frontbackend.java.io.copy; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class CopyDirectoryUsingFileUtils < public static void main(String[] args) throws IOException < File sourceDirectory = new File("/tmp/from"); File destinationDirectory = new File("/tmp/to"); FileUtils.copyDirectory(sourceDirectory, destinationDirectory); >>
This approach allows us to create a single-line solution.
5. Conclusion
This article presented how to copy a directory with files and subdirectories in Java. We used plain Java methods available in java.io and newer java.nio API and one of the third-party libraries for manipulating files: Apache Commons IO .
Example snippets used in this tutorial are available over on GitHub.
More Java I/O related articles are available here.