Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Last active November 16, 2017 22:37
Show Gist options
  • Save masahitojp/af45908f424737b0e10d to your computer and use it in GitHub Desktop.
Save masahitojp/af45908f424737b0e10d to your computer and use it in GitHub Desktop.
package me.masahito;
import java.io.*;
import java.nio.channels.FileChannel;
public class FileCopyMain {
private static void copyFileUsingStream(File source, File dest) throws IOException {
try(
InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(dest)
) {
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
}
}
private static void copyFileUsingRandomAccessFile(File source, File dest) throws IOException {
try(
InputStream is = new FileInputStream(source);
RandomAccessFile raf = new RandomAccessFile(dest, "rw")
) {
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
raf.write(buffer, 0, length);
}
}
}
private static void copyFileUsingChannel(File source, File dest) throws IOException {
try (
FileChannel input = new FileInputStream(source).getChannel();
FileChannel output = new FileOutputStream(dest).getChannel()
) {
input.transferTo(0, input.size(), output);
}
}
public static void main(String[] args) throws IOException {
//copy file conventional way using Stream
final File source = new File("/Users/masahito/tmp/source.data");
File dest = new File("/Users/masahito/tmp/dest.data");
long start = System.nanoTime();
copyFileUsingStream(source, dest);
System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
//copy files using InputStream and RandomAccessFile
dest = new File("/Users/masahito/tmp/destRandomAccessFile.data");
start = System.nanoTime();
copyFileUsingRandomAccessFile(source, dest);
System.out.println("Time taken by RandomAccessFile Copy = "+(System.nanoTime()-start));
//copy files using java.nio FileChannel
dest = new File("/Users/masahito/tmp/destChannel.data");
start = System.nanoTime();
copyFileUsingChannel(source, dest);
System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
}
}
MacBook Pro
10.9
SSDmodel
jdk1.8.0
Time taken by Stream Copy = 6092912000
Time taken by RandomAccessFile Copy = 4220217000
Time taken by Channel Copy = 6136507000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment