Copying files from one directory to another in Java

Viewed 522987

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];

}
34 Answers

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.

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

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();
        }
    }

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();
    }

}

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

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

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();
            }            
        }
    }

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

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) {
            }
        }
    }

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();
        }


    }
}

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();
    }

}

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;
}

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

Related