Java speeds up reading and copying large files

  • 2021-07-24 10:59:05
  • OfStack

File channel (FileChannel) to achieve file replication, for your reference, the specific contents are as follows

Regardless of multithreaded optimization, the fastest method for single-threaded file copy is (the larger the file, the more advantageous this method is, which is generally 30 +% faster than common methods):

Directly on the code:


package test;
 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.nio.channels.FileChannel;

 public class Test {
public static void main(String[] args) {
File source = new File("E:\\tools\\fmw_12.1.3.0.0_wls.jar");
File target = new File("E:\\tools\\fmw_12.1.3.0.0_wls-copy.jar");
long start, end;

start = System.currentTimeMillis();
fileChannelCopy(source, target);
end = System.currentTimeMillis();
System.out.println(" File channel time: " + (end - start) + " Milliseconds ");

start = System.currentTimeMillis();
copy(source, target);
end = System.currentTimeMillis();
System.out.println(" Ordinary buffer time: " + (end - start) + " Milliseconds ");
}

/**
 *  Copy files using file channels 
 * @param source  Source file 
 * @param target  Object file 
 */
 public static void fileChannelCopy(File source, File target) {


  FileInputStream in = null;
  FileOutputStream out = null;
  FileChannel inChannel = null;
  FileChannel outChannel = null;
  try {
  in = new FileInputStream(source);
  out = new FileOutputStream(target);
  inChannel = in.getChannel();// Get the corresponding file channel 
  outChannel = out.getChannel();// Get the corresponding file channel 
  inChannel.transferTo(0, inChannel.size(), outChannel);// Connect the two channels and derive from the inChannel Channel read and then write to outChannel Channel 
 } catch (IOException e) {
  e.printStackTrace();
  } finally {
  try {
   in.close();
   inChannel.close();
   out.close();
   outChannel.close();
  } catch (IOException e) {
   e.printStackTrace();
  }


  }


 }
 
/**
*  Normal buffer replication 
* @param source  Source file 
* @param target  Object file 
*/
public static void copy (File source, File target) {
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(source));
out = new BufferedOutputStream(new FileOutputStream(target));
byte[] buf = new byte[4096];
int i;
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
 }

 }

Related articles: