Home > Java > JavaBase > How to copy files in java?

How to copy files in java?

Release: 2019-12-03 13:35:39
Original
8830 people have browsed it

How to copy files in java?

How to copy files in java: (Recommended: java video tutorial)

1. Use FileStreams copy

This is the most classic way to copy the contents of one file to another file. Use FileInputStream to read the bytes of file A, and use FileOutputStream to write to file B. This is the code for the first method:

private static void copyFileUsingFileStreams(File source, File dest)
        throws IOException {    
    InputStream input = null;    
    OutputStream output = null;    
    try {
           input = new FileInputStream(source);
           output = new FileOutputStream(dest);        
           byte[] buf = new byte[1024];        
           int bytesRead;        
           while ((bytesRead = input.read(buf)) != -1) {
               output.write(buf, 0, bytesRead);
           }
    } finally {
        input.close();
        output.close();
    }
}
Copy after login

As you can see we perform several read and write operations on the try data, so this should be an inefficient one, as we will see in the next method new way.

2. Use FileChannel to copy

Java NIO includes the transferFrom method, which according to the document should be faster than file stream copying. This is the code for the second method:

private static void copyFileUsingFileChannels(File source, File dest) throws IOException {    
        FileChannel inputChannel = null;    
        FileChannel outputChannel = null;    
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}
Copy after login

3. Use Commons IO to copy

Apache Commons IO provides a copy file method in its FileUtils Class that can be used to copy a file to another location. It's very convenient to use the Apache Commons FileUtils class that you already use in your project. Basically, this class uses Java NIO FileChannel internally. This is the code of the third method:

 private static void copyFileUsingApacheCommonsIO(File source, File dest)
         throws IOException {
     FileUtils.copyFile(source, dest);
 }
Copy after login

The core code of this method is as follows:

private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel input = null;
        FileChannel output = null;
        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            input  = fis.getChannel();
            output = fos.getChannel();
            long size = input.size();
            long pos = 0;
            long count = 0;
            while (pos < size) {
                count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
                pos += output.transferFrom(input, pos, count);
            }
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(fis);
        }

        if (srcFile.length() != destFile.length()) {
            throw new IOException("Failed to copy full contents from '" +
                    srcFile + "' to '" + destFile + "'");
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }
Copy after login

It can be seen that the principle of using Apache Commons IO to copy files is the second method above: use FileChannel copy

4. Use the Files class of Java7 to copy

If you have some experience in Java 7 you may know that you can use Files class file copy method, copy from one file to another file. This is the code of the fourth method:

 private static void copyFileUsingJava7Files(File source, File dest)
         throws IOException {    
         Files.copy(source.toPath(), dest.toPath());
}
Copy after login

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of How to copy files in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template