Memory Mapped I/O Example: New Way
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class NewFileCopier {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java NewFileCopier infile outfile");
return;
}
try {
copy(args[0], args[1]);
}
catch (IOException e) {
System.err.println(e);
}
}
public static void copy(String inFile, String outFile)
throws IOException {
FileInputStream fin = null;
RandomAccessFile fout = null;
try {
fin = new FileInputStream(inFile);
fout = new RandomAccessFile(outFile, "rw");
FileChannel in = fin.getChannel();
FileChannel out = fout.getChannel();
MappedByteBuffer input = in.map(FileChannel.MapMode.READ_ONLY, 0, in.size());
MappedByteBuffer output = out.map(FileChannel.MapMode.READ_WRITE, 0, in.size());
output.put(input);
}
finally {
try {
if (fin != null) fin.close();
}
catch (IOException e) {}
try {
if (fout != null) fout.close();
}
catch (IOException e) {}
}
}
}