182

I want to copy files from one directory to another (subdirectory) using Java. I have a directory, dir, with text files. I iterate over the first 20 files in dir, and want to copy them to another directory in the dir directory, which I have created right before the iteration. In the code, I want to copy the review (which represents the ith text file or review) to trainingDir. How can I do this? There seems not to be such a function (or I couldn't find). Thank you.

boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
    File review = reviews[i];

}
akarnokd
  • 69,132
  • 14
  • 157
  • 192
user42155
  • 48,965
  • 27
  • 59
  • 60
  • So, you have a directory full of files and you want copy these files only? No recursion on the input side - e.g copy everything from subdirs into a main dir? – akarnokd Jul 18 '09 at 12:07
  • Yes, exactly. I am interested in both just copying or moving these files to another directory (though in the post I have asked just for copying). – user42155 Jul 18 '09 at 12:17
  • 3
    Update from the future. Java 7 has a feature from the [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) class to copy files. Here is another post about it http://stackoverflow.com/questions/16433915/how-to-copy-file-from-one-location-to-another-location – KevinL Oct 07 '13 at 13:19

34 Answers34

192

For now this should solve your problem

File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
    FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
    e.printStackTrace();
}

FileUtils class from apache commons-io library, available since version 1.2.

Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.

aliteralmind
  • 19,847
  • 17
  • 77
  • 108
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • FileUtils didn't work for me. source i taken as "E:\\Users\\users.usr" and destination as "D:\\users.usr". what could be the problem? – JAVA Mar 04 '17 at 15:19
  • 5
    Nice solution, for me , it works when I change `FileUtils.copyDirectory(source,dest)` to `FileUtils.copyFile(source, dest)`, this can create directory if it does not exist – yuqizhang May 13 '19 at 09:55
  • FileUtils.copyDirectory only copies files in directory not subdirectories. FileUtils.copyDirectoryStructure copies all files and subdirectories – Homayoun Behzadian Jul 15 '19 at 09:30
46

In Java 7, there is a standard method to copy files in java:

Files.copy.

It integrates with O/S native I/O for high performance.

See my A on Standard concise way to copy a file in Java? for a full description of usage.

Community
  • 1
  • 1
Glen Best
  • 22,769
  • 3
  • 58
  • 74
  • 8
    This does not address the question of copying whole directories. – Charlie Feb 06 '18 at 08:00
  • Yes it does...if you follow the link. Don't forget that a "File" in java can represent a directory or file, it is just a reference. – gagarwa Jan 31 '19 at 21:38
  • 1
    "If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied)" – yurez Apr 08 '19 at 13:36
45

There is no file copy method in the Standard API (yet). Your options are:

  • Write it yourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use FileChannel.transferTo()
  • User Apache Commons' FileUtils
  • Wait for NIO2 in Java 7
DavidG
  • 72
  • 1
  • 1
  • 7
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
31

The example below from Java Tips is rather straight forward. I have since switched to Groovy for operations dealing with the file system - much easier and elegant. But here is the Java Tips one I used in the past. It lacks the robust exception handling that is required to make it fool-proof.

 public 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);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
    }
Brian
  • 13,412
  • 10
  • 56
  • 82
  • Thank you, but I don't want to copy the directory - only the files in it. Now I get error messages java.io.FileNotFoundException: (the path to trDir) (Is a directory) This is what it only says. I have used the method like this: copyDirectory(review, trDir); – user42155 Jul 18 '09 at 10:48
  • Thanks, better to check if `sourceLocation.exists()` in case to prevent `java.io.FileNotFoundException` – Sdghasemi Jul 19 '15 at 16:13
23

If you want to copy a file and not move it you can code like this.

private static void copyFile(File sourceFile, File destFile)
        throws IOException {
    if (!sourceFile.exists()) {
        return;
    }
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        destination.transferFrom(source, 0, source.size());
    }
    if (source != null) {
        source.close();
    }
    if (destination != null) {
        destination.close();
    }

}
Janusz
  • 187,060
  • 113
  • 301
  • 369
  • Hi, I have tried this, but I obtain error messages: java.io.FileNotFoundException: ...path to trDir... (Is a directory) Everything in my file and folders seem to be ok. Do you know what it going wrong, and why I get this? – user42155 Jul 18 '09 at 10:52
  • But isn't there a Windows bug around the transferFrom not able to copy streams larger than 64MB in one piece? http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4938442 fix http://www.rgagnon.com/javadetails/java-0064.html – akarnokd Jul 18 '09 at 12:06
  • I am using Ubuntu 8.10, so this shouldn't be the problem. – user42155 Jul 18 '09 at 12:18
  • If you are sure your code won't ever run on different platform. – akarnokd Jul 18 '09 at 17:26
  • @gemm the destfile has to be the exact path were the file should be copied to. This means including the new filename not only the directory you want to copy the file to. – Janusz Jul 18 '09 at 17:41
  • @Janusz how do you use this method to not copy but to move it totally? – StuStirling Oct 16 '12 at 14:05
20

apache commons Fileutils is handy. you can do below activities.

  1. copying file from one directory to another directory.

    use copyFileToDirectory(File srcFile, File destDir)

  2. copying directory from one directory to another directory.

    use copyDirectory(File srcDir, File destDir)

  3. copying contents of one file to another

    use static void copyFile(File srcFile, File destFile)

Community
  • 1
  • 1
Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40
19

Spring Framework has many similar util classes like Apache Commons Lang. So there is org.springframework.util.FileSystemUtils

File src = new File("/home/user/src");
File dest = new File("/home/user/dest");
FileSystemUtils.copyRecursively(src, dest);
Ihor Rybak
  • 3,091
  • 2
  • 25
  • 32
10

You seem to be looking for the simple solution (a good thing). I recommend using Apache Common's FileUtils.copyDirectory:

Copies a whole directory to a new location preserving the file dates.

This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.

The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.

Your code could like nice and simple like this:

File trgDir = new File("/tmp/myTarget/");
File srcDir = new File("/tmp/mySource/");

FileUtils.copyDirectory(srcDir, trgDir);
Stu Thompson
  • 38,370
  • 19
  • 110
  • 156
10
File sourceFile = new File("C:\\Users\\Demo\\Downloads\\employee\\"+img);
File destinationFile = new File("\\images\\" + sourceFile.getName());

FileInputStream fileInputStream = new FileInputStream(sourceFile);
FileOutputStream fileOutputStream = new FileOutputStream(
                destinationFile);

int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
    fileOutputStream.write(bufffer, 0, bufferSize);
}
fileInputStream.close();
fileOutputStream.close();
demongolem
  • 9,474
  • 36
  • 90
  • 105
Shaktisinh Jadeja
  • 1,427
  • 1
  • 17
  • 22
10

Java 8

Path sourcepath = Paths.get("C:\\data\\temp\\mydir");
Path destinationepath = Paths.get("C:\\data\\temp\\destinationDir");        
Files.walk(sourcepath)
         .forEach(source -> copy(source, destinationepath.resolve(sourcepath.relativize(source)))); 

Copy Method

static void copy(Path source, Path dest) {
    try {
        Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
informatik01
  • 16,038
  • 10
  • 74
  • 104
Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104
8

Apache commons FileUtils will be handy, if you want only to move files from the source to target directory rather than copy the whole directory, you can do:

for (File srcFile: srcDir.listFiles()) {
    if (srcFile.isDirectory()) {
        FileUtils.copyDirectoryToDirectory(srcFile, dstDir);
    } else {
        FileUtils.copyFileToDirectory(srcFile, dstDir);
    }
}

If you want to skip directories, you can do:

for (File srcFile: srcDir.listFiles()) {
    if (!srcFile.isDirectory()) {
        FileUtils.copyFileToDirectory(srcFile, dstDir);
    }
}
demongolem
  • 9,474
  • 36
  • 90
  • 105
saste
  • 710
  • 2
  • 11
  • 19
8
import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);

Source: https://docs.oracle.com/javase/tutorial/essential/io/copy.html

gagarwa
  • 1,426
  • 1
  • 15
  • 28
  • 1
    From the source: _Directories can be copied. **However, files inside the directory are not copied**, so the new directory is empty even when the original directory contains files._ – Luke Feb 23 '23 at 05:19
7

Inspired by Mohit's answer in this thread. Applicable only for Java 8.

The following can be used to copy everything recursively from one folder to another:

public static void main(String[] args) throws IOException {
    Path source = Paths.get("/path/to/source/dir");
    Path destination = Paths.get("/path/to/dest/dir");

    List<Path> sources = Files.walk(source).collect(toList());
    List<Path> destinations = sources.stream()
            .map(source::relativize)
            .map(destination::resolve)
            .collect(toList());

    for (int i = 0; i < sources.size(); i++) {
        Files.copy(sources.get(i), destinations.get(i));
    }
}

Stream-style FTW.

Upd 2019-06-10: important note - close the stream (e.g. using try-with-resource) acquired by Files.walk call. Thanks to @jannis for the point.

  • Awesome!! use parallel Stream if anyone want to copy directory which has million of file. I can show the progress of copying files easily, but in JAVA 7 nio copyDirectory command, for big directory i was unable to show progress for users. – Aqeel Haider Jan 07 '18 at 03:08
  • 1
    I suggest closing the stream returned by `Files.walk(source)` as advised in [the docs](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-) or [you might get in trouble](https://stackoverflow.com/q/56290320/4494577) – jannis Jun 07 '19 at 13:34
4

Below is Brian's modified code which copies files from source location to destination location.

public class CopyFiles {
 public static void copyFiles(File sourceLocation , File targetLocation)
    throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }
            File[] files = sourceLocation.listFiles();
            for(File file:files){
                InputStream in = new FileInputStream(file);
                OutputStream out = new FileOutputStream(targetLocation+"/"+file.getName());

                // Copy the bits from input stream to output stream
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            }            
        }
    }
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • Works fine but is missing a recursive logic to handle subdirectories. I suggest to do `if (file.isDirectory()) { copyFiles(file.getAbsolutePath(), targetLocation.getAbsolutePath() +"/"+file.getName()); }` and to put all the remaining stuff that is done in the `for`-loop into the `else`-branch – nhaggen Sep 17 '20 at 12:27
3

You can workaround with copy the source file to a new file and delete the original.

public class MoveFileExample {

 public static void main(String[] args) {   

    InputStream inStream = null;
    OutputStream outStream = null;

    try {

        File afile = new File("C:\\folderA\\Afile.txt");
        File bfile = new File("C:\\folderB\\Afile.txt");

        inStream = new FileInputStream(afile);
        outStream = new FileOutputStream(bfile);

        byte[] buffer = new byte[1024];

        int length;
        //copy the file content in bytes 
        while ((length = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, length);
        }

        inStream.close();
        outStream.close();

        //delete the original file
        afile.delete();

        System.out.println("File is copied successful!");

    } catch(IOException e) {
        e.printStackTrace();
    }
 }
}
Robert
  • 5,278
  • 43
  • 65
  • 115
Guy Ben-Shahar
  • 231
  • 1
  • 11
3

This prevents file from being corrupted!

Just download the following jar!
Jar File
Download Page

import org.springframework.util.FileCopyUtils;

private static void copyFile(File source, File dest) throws IOException {
    //This is safe and don't corrupt files as FileOutputStream does
    File src = source;
    File destination = dest;
    FileCopyUtils.copy(src, dest);
}
Yash
  • 369
  • 5
  • 18
2
File dir = new File("D:\\mital\\filestore");
File[] files = dir.listFiles(new File_Filter("*"+ strLine + "*.txt"));
for (File file : files){    
    System.out.println(file.getName());

    try {
        String sourceFile=dir+"\\"+file.getName();
        String destinationFile="D:\\mital\\storefile\\"+file.getName();
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        FileOutputStream fileOutputStream = new FileOutputStream(
                        destinationFile);
        int bufferSize;
        byte[] bufffer = new byte[512];
        while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
            fileOutputStream.write(bufffer, 0, bufferSize);
        }
        fileInputStream.close();
        fileOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
ajon
  • 7,868
  • 11
  • 48
  • 86
mital
  • 21
  • 1
1

The NIO classes make this pretty simple.

http://www.javalobby.org/java/forums/t17036.html

Nate
  • 2,407
  • 22
  • 22
1

i use the following code to transfer a uploaded CommonMultipartFile to a folder and copy that file to a destination folder in webapps (i.e) web project folder,

    String resourcepath = "C:/resources/images/" + commonsMultipartFile.getOriginalFilename();

    File file = new File(resourcepath);
    commonsMultipartFile.transferTo(file);

    //Copy File to a Destination folder
    File destinationDir = new File("C:/Tomcat/webapps/myProject/resources/images/");
    FileUtils.copyFileToDirectory(file, destinationDir);
Romain Francois
  • 17,432
  • 3
  • 51
  • 77
lk.annamalai
  • 403
  • 7
  • 14
1

Copy file from one directory to another directory...

FileChannel source=new FileInputStream(new File("source file path")).getChannel();
FileChannel desti=new FileOutputStream(new File("destination file path")).getChannel();
desti.transferFrom(source, 0, source.size());
source.close();
desti.close();
Rao
  • 20,781
  • 11
  • 57
  • 77
Rajneesh Mishra
  • 228
  • 4
  • 10
1

here is simply a java code to copy data from one folder to another, you have to just give the input of the source and destination.

import java.io.*;

public class CopyData {
static String source;
static String des;

static void dr(File fl,boolean first) throws IOException
{
    if(fl.isDirectory())
    {
        createDir(fl.getPath(),first);
        File flist[]=fl.listFiles();
        for(int i=0;i<flist.length;i++)
        {

            if(flist[i].isDirectory())
            {
                dr(flist[i],false);
            }

            else
            {

                copyData(flist[i].getPath());
            }
        }
    }

    else
    {
        copyData(fl.getPath());
    }
}

private static void copyData(String name) throws IOException {

        int i;
        String str=des;
        for(i=source.length();i<name.length();i++)
        {
            str=str+name.charAt(i);
        }
        System.out.println(str);
        FileInputStream fis=new FileInputStream(name);
        FileOutputStream fos=new FileOutputStream(str);
        byte[] buffer = new byte[1024];
        int noOfBytes = 0;
         while ((noOfBytes = fis.read(buffer)) != -1) {
             fos.write(buffer, 0, noOfBytes);
         }


}

private static void createDir(String name, boolean first) {

    int i;

    if(first==true)
    {
        for(i=name.length()-1;i>0;i--)
        {
            if(name.charAt(i)==92)
            {
                break;
            }
        }

        for(;i<name.length();i++)
        {
            des=des+name.charAt(i);
        }
    }
    else
    {
        String str=des;
        for(i=source.length();i<name.length();i++)
        {
            str=str+name.charAt(i);
        }
        (new File(str)).mkdirs();
    }

}

public static void main(String args[]) throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("program to copy data from source to destination \n");
    System.out.print("enter source path : ");
    source=br.readLine();
    System.out.print("enter destination path : ");
    des=br.readLine();
    long startTime = System.currentTimeMillis();
    dr(new File(source),true);
    long endTime   = System.currentTimeMillis();
    long time=endTime-startTime;
    System.out.println("\n\n Time taken = "+time+" mili sec");
}

}

this a working code for what you want..let me know if it helped

Nikunj Gupta
  • 126
  • 2
  • 8
1

Use

org.apache.commons.io.FileUtils

It's so handy

Jay D
  • 3,263
  • 4
  • 32
  • 48
Bhimesh
  • 27
  • 1
  • 4
    If you're going to post an answer suggesting a library, it would be nice if you would actually explain how to use it instead of merely mentioning its name. – Pops Dec 06 '11 at 22:46
1

Best way as per my knowledge is as follows:

    public static void main(String[] args) {

    String sourceFolder = "E:\\Source";
    String targetFolder = "E:\\Target";
    File sFile = new File(sourceFolder);
    File[] sourceFiles = sFile.listFiles();
    for (File fSource : sourceFiles) {
        File fTarget = new File(new File(targetFolder), fSource.getName());
        copyFileUsingStream(fSource, fTarget);
        deleteFiles(fSource);
    }
}

    private static void deleteFiles(File fSource) {
        if(fSource.exists()) {
            try {
                FileUtils.forceDelete(fSource);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void copyFileUsingStream(File source, File dest) {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } catch (Exception ex) {
            System.out.println("Unable to copy file:" + ex.getMessage());
        } finally {
            try {
                is.close();
                os.close();
            } catch (Exception ex) {
            }
        }
    }
Pankaj
  • 21
  • 4
0

You can use the following code to copy files from one directory to another

// parent folders of dest must exist before calling this function
public static void copyTo( File src, File dest ) throws IOException {
     // recursively copy all the files of src folder if src is a directory
     if( src.isDirectory() ) {
         // creating parent folders where source files is to be copied
         dest.mkdirs();
         for( File sourceChild : src.listFiles() ) {
             File destChild = new File( dest, sourceChild.getName() );
             copyTo( sourceChild, destChild );
         }
     } 
     // copy the source file
     else {
         InputStream in = new FileInputStream( src );
         OutputStream out = new FileOutputStream( dest );
         writeThrough( in, out );
         in.close();
         out.close();
     }
 }
Varun Bhatia
  • 4,326
  • 32
  • 46
0
    File file = fileChooser.getSelectedFile();
    String selected = fc.getSelectedFile().getAbsolutePath();
     File srcDir = new File(selected);
     FileInputStream fii;
     FileOutputStream fio;
    try {
         fii = new FileInputStream(srcDir);
         fio = new FileOutputStream("C:\\LOvE.txt");
         byte [] b=new byte[1024];
         int i=0;
        try {
            while ((fii.read(b)) > 0)
            {

              System.out.println(b);
              fio.write(b);
            }
            fii.close();
            fio.close();
Nithin
  • 1
0

following code to copy files from one directory to another

File destFile = new File(targetDir.getAbsolutePath() + File.separator
    + file.getName());
try {
  showMessage("Copying " + file.getName());
  in = new BufferedInputStream(new FileInputStream(file));
  out = new BufferedOutputStream(new FileOutputStream(destFile));
  int n;
  while ((n = in.read()) != -1) {
    out.write(n);
  }
  showMessage("Copied " + file.getName());
} catch (Exception e) {
  showMessage("Cannot copy file " + file.getAbsolutePath());
} finally {
  if (in != null)
    try {
      in.close();
    } catch (Exception e) {
    }
  if (out != null)
    try {
      out.close();
    } catch (Exception e) {
    }
}
Dhrumil Shah
  • 736
  • 6
  • 15
0
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFiles {
    private File targetFolder;
    private int noOfFiles;
    public void copyDirectory(File sourceLocation, String destLocation)
            throws IOException {
        targetFolder = new File(destLocation);
        if (sourceLocation.isDirectory()) {
            if (!targetFolder.exists()) {
                targetFolder.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i = 0; i < children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]),
                        destLocation);

            }
        } else {

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetFolder + "\\"+ sourceLocation.getName(), true);
            System.out.println("Destination Path ::"+targetFolder + "\\"+ sourceLocation.getName());            
            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            noOfFiles++;
        }
    }

    public static void main(String[] args) throws IOException {

        File srcFolder = new File("C:\\sourceLocation\\");
        String destFolder = new String("C:\\targetLocation\\");
        CopyFiles cf = new CopyFiles();
        cf.copyDirectory(srcFolder, destFolder);
        System.out.println("No Of Files got Retrieved from Source ::"+cf.noOfFiles);
        System.out.println("Successfully Retrieved");
    }
}
0

Not even that complicated and no imports required in Java 7:

The renameTo( ) method changes the name of a file:

public boolean renameTo( File destination)

For example, to change the name of the file src.txt in the current working directory to dst.txt, you would write:

File src = new File(" src.txt"); File dst = new File(" dst.txt"); src.renameTo( dst); 

That's it.

Reference:

Harold, Elliotte Rusty (2006-05-16). Java I/O (p. 393). O'Reilly Media. Kindle Edition.

Newd
  • 2,174
  • 2
  • 17
  • 31
0

You can use the following code to copy files from one directory to another

public static void copyFile(File sourceFile, File destFile) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(sourceFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        } catch(Exception e){
            e.printStackTrace();
        }
        finally {
            in.close();
            out.close();
        }
    }
0

Following recursive function I have written, if it helps anyone. It will copy all the files inside sourcedirectory to destinationDirectory.

example:

rfunction("D:/MyDirectory", "D:/MyDirectoryNew", "D:/MyDirectory");

public static void rfunction(String sourcePath, String destinationPath, String currentPath) {
    File file = new File(currentPath);
    FileInputStream fi = null;
    FileOutputStream fo = null;

    if (file.isDirectory()) {
        String[] fileFolderNamesArray = file.list();
        File folderDes = new File(destinationPath);
        if (!folderDes.exists()) {
            folderDes.mkdirs();
        }

        for (String fileFolderName : fileFolderNamesArray) {
            rfunction(sourcePath, destinationPath + "/" + fileFolderName, currentPath + "/" + fileFolderName);
        }
    } else {
        try {
            File destinationFile = new File(destinationPath);

            fi = new FileInputStream(file);
            fo = new FileOutputStream(destinationPath);
            byte[] buffer = new byte[1024];
            int ind = 0;
            while ((ind = fi.read(buffer))>0) {
                fo.write(buffer, 0, ind);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if (null != fi) {
                try {
                    fi.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != fo) {
                try {
                    fo.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
Yogesh Sanchihar
  • 1,080
  • 18
  • 25
0

If you don't want to use external libraries and you want to use the java.io instead of java.nio classes, you can use this concise method to copy a folder and all its content:

/**
 * Copies a folder and all its content to another folder. Do not include file separator at the end path of the folder destination.
 * @param folderToCopy The folder and it's content that will be copied
 * @param folderDestination The folder destination
 */
public static void copyFolder(File folderToCopy, File folderDestination) {
    if(!folderDestination.isDirectory() || !folderToCopy.isDirectory())
        throw new IllegalArgumentException("The folderToCopy and folderDestination must be directories");

    folderDestination.mkdirs();

    for(File fileToCopy : folderToCopy.listFiles()) {
        File copiedFile = new File(folderDestination + File.separator + fileToCopy.getName());

        try (FileInputStream fis = new FileInputStream(fileToCopy);
             FileOutputStream fos = new FileOutputStream(copiedFile)) {

            int read;
            byte[] buffer = new byte[512];

            while ((read = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
Domenico
  • 1,331
  • 18
  • 22
0

I provided an alternate solution without the need to use a third party, such as apache FileUtils. This can be done through the command line.

I tested this out on Windows and it works for me. A Linux solution follows.

Here I am utilizing Windows xcopy command to copy all files including subdirectories. The parameters that I pass are defined as per below.

  • /e - Copies all subdirectories, even if they are empty.
  • /i - If Source is a directory or contains wildcards and Destination does not exist, xcopy assumes Destination specifies a directory name and creates a new directory. Then, xcopy copies all specified files into the new directory.
  • /h - Copies files with hidden and system file attributes. By default, xcopy does not copy hidden or system files

My example(s) utilizes the ProcessBuilder class to construct a process to execute the copy(xcopy & cp) commands.

Windows:

String src = "C:\\srcDir";
String dest = "C:\\destDir";
List<String> cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");
try {
    Process proc = new ProcessBuilder(cmd).start();
    BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = inp.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Linux:

String src = "srcDir/";
String dest = "~/destDir/";
List<String> cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);
try {
    Process proc = new ProcessBuilder(cmd).start();
    BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = inp.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Or a combo that can work on both Windows or Linux environments.

private static final String OS = System.getProperty("os.name");
private static String src = null;
private static String dest = null;
private static List<String> cmd = null;

public static void main(String[] args) {
    if (OS.toLowerCase().contains("windows")) { // setup WINDOWS environment
        src = "C:\\srcDir";
        dest = "C:\\destDir";
        cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");

        System.out.println("on: " + OS);
    } else if (OS.toLowerCase().contains("linux")){ // setup LINUX environment
        src = "srcDir/";
        dest = "~/destDir/";
        cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);

        System.out.println("on: " + OS);
    }

    try {
        Process proc = new ProcessBuilder(cmd).start();
        BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = null;
        while ((line = inp.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}
0

For JRE6/Java 6 or higher if do you need sync two folders, do you can use this code "syncFolder", you can remove the ProgressMonitor parameter.

The method returns a recursive string description of errors, it returns empty if there are no problems.

public static String syncFolder(File folderFrom, File folderTo, ProgressMonitor monitor) {
    String res = "";
    File[] fromFiles = folderFrom.listFiles();
    float actualPercent = 0;
    float iterationPercent = 100f / fromFiles.length;
    monitor.setProgress(0);
    for (File remoteFile : fromFiles) {
        monitor.setNote("Sincronizando " + remoteFile.getName());
        String mirrorFilePath = folderTo.getAbsolutePath() + "\\" + remoteFile.getName();
        if (remoteFile.isDirectory()) {
            File mirrorFolder = new File(mirrorFilePath);
            if (!mirrorFolder.exists() && !mirrorFolder.mkdir()) {
                res = res + "No se pudo crear el directorio " + mirrorFolder.getAbsolutePath() + "\n";
            }
            res = res + syncFolder(remoteFile, mirrorFolder, monitor);
        } else {
            boolean copyReplace = true;
            File mirrorFile = new File(mirrorFilePath);
            if (mirrorFile.exists()) {
                boolean eq = HotUtils.sameFile(remoteFile, mirrorFile);
                if (!eq) {
                    res = res + "Sincronizado: " + mirrorFile.getAbsolutePath() + " - " + remoteFile.getAbsolutePath() + "\n";
                    if (!mirrorFile.delete()) {
                        res = res + "Error - El archivo no pudo ser eliminado\n";
                    }
                } else {
                    copyReplace = false;
                }
            }
            if (copyReplace) {
                copyFile(remoteFile, mirrorFile);
            }
            actualPercent = actualPercent + iterationPercent;
            int resPercent = (int) actualPercent;
            if (resPercent != 100) {
                monitor.setProgress(resPercent);
            }
        }
    }
    return res;
}
    
    public static boolean sameFile(File a, File b) {
    if (a == null || b == null) {
        return false;
    }

    if (a.getAbsolutePath().equals(b.getAbsolutePath())) {
        return true;
    }

    if (!a.exists() || !b.exists()) {
        return false;
    }
    if (a.length() != b.length()) {
        return false;
    }
    boolean eq = true;

    FileChannel channelA = null;
    FileChannel channelB = null;
    try {
        channelA = new RandomAccessFile(a, "r").getChannel();
        channelB = new RandomAccessFile(b, "r").getChannel();

        long channelsSize = channelA.size();
        ByteBuffer buff1 = channelA.map(FileChannel.MapMode.READ_ONLY, 0, channelsSize);
        ByteBuffer buff2 = channelB.map(FileChannel.MapMode.READ_ONLY, 0, channelsSize);
        for (int i = 0; i < channelsSize; i++) {
            if (buff1.get(i) != buff2.get(i)) {
                eq = false;
                break;
            }
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(HotUtils.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HotUtils.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (channelA != null) {
                channelA.close();
            }
            if (channelB != null) {
                channelB.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(HotUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return eq;
}

public static boolean copyFile(File from, File to) {
    boolean res = false;
    try {
        final FileInputStream inputStream = new FileInputStream(from);
        final FileOutputStream outputStream = new FileOutputStream(to);
        final FileChannel inChannel = inputStream.getChannel();
        final FileChannel outChannel = outputStream.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
        inChannel.close();
        outChannel.close();
        inputStream.close();
        outputStream.close();
        res = true;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(SyncTask.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SyncTask.class.getName()).log(Level.SEVERE, null, ex);
    }
    return res;
}
-4

you use renameTo() – not obvious, I know ... but it's the Java equivalent of move ...

Joey
  • 344,408
  • 85
  • 689
  • 683
phatmanace
  • 4,671
  • 3
  • 24
  • 29