Although Java provides an IO operation class that can handle files. But there is no way to copy files. Copying files is an important operation when your program has to deal with many files related. However, there are several ways to copy Java files, and the following are the most popular methods.
1. Copy using FileStreams
This is the most classic way to copy the contents of one file into another. Use FileInputStream to read 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)) > 0) { output.write(buf, 0, bytesRead); } } finally { input.close(); output.close(); } } As you can see we perform several read and write operations to try the data, so this should be an inefficient way, and the next method we will see a new way.
2. Copy using FileChannel
Java NIO includes the transferFrom method, which should be copied faster than file streams based on the document. Here 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(); } }3. Copy using Commons IO
Apache Commons IO provides a copy file method in its FileUtils class, which can be used to copy one file to another. It is very convenient when using the Apache Commons FileUtils class when you are already using your project. Basically, this class uses Java NIO FileChannel internals. This is the code for the third method:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { FileUtils.copyFile(source, dest); }4. Copy using Java7's Files class
If you have some experience in Java 7 you may know that you can use the copy method to copy from one file to another. This is the code for the fourth method:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException { Files.copy(source.toPath(), dest.toPath()); }Let’s take a look at the implementation code for copying a java file to another directory. The specific code is as follows:
package com.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;public class TestHtml {/** * Copy a single file* @param oldPath String Original file path such as: c:/fqf.txt * @param newPath String Path after copying is: f:/fqf.txt * @return boolean */ public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { //InputStream inStream = new FileInputStream(oldPath); //Read in the original file FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //Bytes file size System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("Error copying a single file"); e.printStackTrace();}}/** * Copy the entire folder content* @param oldPath String Original file path such as: c:/fqf * @param newPath String Path after copying is: f:/fqf/ff * @return boolean */ public void copyFolder(String oldPath, String newPath) {try { (new File(newPath)).mkdirs(); //If the folder does not exist, create a new folder File a=new File(oldPath); String[] file=a.list(); File temp=null; for (int i = 0; i < file.length; i++) { if(oldPath.endsWith(File.separator)){ temp=new File(oldPath+file[i]); } else{ temp=new File(oldPath+File.separator+file[i]); } if(temp.isFile()){ FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString()); byte[] b = new byte[1024 * 5]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()){//If it is a subfolder copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); } } } catch (Exception e) { System.out.println("Error copying the entire folder content operation"); e.printStackTrace();}}public static void main(String[] args)throws Exception {// // This is your source file, which itself exists // File beforefile = new File("C:/Users/Administrator/Desktop/Untitled-2.html");////// //This is the file you want to save, it is customized, it does not exist in itself // File afterfile = new File("C:/Users/Administrator/Desktop/jiekou0/Untitled-2.html");//// // Define the file input stream to read the beforefile file// FileInputStream fis = new FileInputStream(beforefile);//// Define the file output stream to write information into the afterfile file// FileOutputStream fos = new FileOutputStream(afterfile);//// // File cache area// byte[] b = new byte[1024];// // Read the file stream information in the file cache area. If the reading result is not -1, it means that the file has not been read, and it has been read.// while(fis.read(b)!=-1){// // Write the content in the cache area to the afterfile file// fos.write(b);// fos.flush();// }String oldPath="C:/Users/Administrator/Desktop/Untitled-2.html";String newPath="C:/Users/Administrator/Desktop/jiekou0/Untitled-2.html";TestHtml t=new TestHtml();t.copyFile(oldPath, newPath);}}Summarize
The above are the 4 ways to copy files in Java and the example code of copying files to another directory introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!