I am starting a Java programmer.
Today I practiced how to copy a file in java and tried to follow this guide
http://www.journaldev.com/861/4-ways-to-copy-file-in-java
Having finished this tutorial, I launched JMH Benchmark to check performance, with a 57 MB txt file.
And there is a performance gap between nioFiles and NIOChannel, more than I expected.
Benchmark Mode Cnt Score Error Units
CompressTest.fileCopyUsingNIOChannelClass thrpt 10 22.465 ± 2.996 ops/s
CompressTest.fileCopyWithNIOFiles thrpt 10 0.843 ± 0.488 ops/s
Here is the code I used
@Warmup(iterations = 5, time = 1000, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 1000, timeUnit = TimeUnit.MILLISECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class CompressTest
{
final static Path source = Paths.get("c:/temp/system.out.lambda.txt");
final static Path target = Paths.get("c:/temp/copied.lambda.txt");
public static void main(String[] args) throws RunnerException, IOException {
Main.main(args);
}
@Benchmark
public static void fileCopyWithNIOFiles() throws IOException{
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
@Benchmark
public static void fileCopyUsingNIOChannelClass() throws IOException
{
File fileToCopy = new File("c:/temp/system.out.lambda.txt");
FileInputStream inputStream = new FileInputStream(fileToCopy);
FileChannel inChannel = inputStream.getChannel();
File newFile = new File("c:/temp/testcopied.txt");
FileOutputStream outputStream = new FileOutputStream(newFile);
FileChannel outChannel = outputStream.getChannel();
inChannel.transferTo(0, fileToCopy.length(), outChannel);
inputStream.close();
outputStream.close();
}
}
So, I want to ask if I did something wrong? or could you explain why this happened?
Someone asked, so I tried another file. The result is an avi 348MB file and the following result.
Benchmark Mode Cnt Score Error Units
CompressTest.fileCopyUsingNIOChannelClass thrpt 10 3.142 ± 0.738 ops/s
CompressTest.fileCopyWithNIOFiles thrpt 10 1.991 ± 0.350 ops/s
Copying a file with nioFile is slower than using NIOChannel.
, . txt 57 10.
Benchmark Mode Cnt Score Error Units
CompressTest.fileCopyUsingNIOChannelClass thrpt 10 23.442 ± 3.224 ops/s
CompressTest.fileCopyWithNIOFiles thrpt 10 12.328 ± 2.128 ops/s
, , nioFile NIOChannel.
P.S.: , , . java, .