package read; import java.io.*; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; /** * Created by joyce on 2019/9/23. */ public class FormerReader { public static void main(String [] f) throws Exception { File fileIn = new File("/Users/joyce/Downloads/java.pdf"); //打开源文件 File fileOut = new File("/Users/joyce/Downloads/target.pdf"); // 普通stream方式 long formerStart = System.currentTimeMillis(); FileInputStream streamln = new FileInputStream (fileIn); FileOutputStream streamOut = new FileOutputStream (fileOut); int c; while ((c = streamln.read()) != -1) { streamOut.write(c); } streamln.close(); streamOut.close(); long formerEnd = System.currentTimeMillis(); System.out.println((formerStart-formerEnd)/1000); // nio MappedByteBuffer formerStart = System.currentTimeMillis(); long len = fileIn.length(); FileChannel fileChannel = new RandomAccessFile(fileIn, "r").getChannel(); MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, len); MappedByteBuffer mappedByteBufferout = new RandomAccessFile(fileOut, "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, len); for (int offset = 0; offset < len; offset++) { byte b = mappedByteBuffer.get(); mappedByteBufferout.put(b); } formerEnd = System.currentTimeMillis(); System.out.println((formerStart-formerEnd)/1000); } }
-283
0
文件26M