1 package com.nio;
2
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.RandomAccessFile;
6 import java.nio.ByteBuffer;
7 import java.nio.MappedByteBuffer;
8 import java.nio.channels.FileChannel;
9 import java.nio.channels.FileChannel.MapMode;
10
11 /**
12 * 比较IO操作的性能比较:
13 * 1、内存映射最快
14 * 2、NIO读写文件
15 * 3、使用了缓存的IO流
16 * 4、无缓存的IO流
17 *
18 * @author vince
19 * @description
20 */
21 public class CopyFileDemo {
22
23
24 private static void randomAccessFileCopy() throws Exception{
25 RandomAccessFile in = new RandomAccessFile("c:\\3D0.jpg","r");
26 RandomAccessFile out = new RandomAccessFile("c:\\test\\3D0.jpg","rw");
27
28 FileChannel fcIn = in.getChannel();
29 FileChannel fcOut = out.getChannel();
30
31 long size = fcIn.size();//输入流的字节大小
32 //输入流的缓冲区
33 MappedByteBuffer inBuf = fcIn.map(MapMode.READ_ONLY, 0, size);
34 //输出流的缓冲区
35 MappedByteBuffer outBuf = fcOut.map(MapMode.READ_WRITE, 0, size);
36
37 for(int i=0;i<size;i++){
38 outBuf.put(inBuf.get());
39 }
40
41 //关闭(关闭通道时会写入数据块)
42 fcIn.close();
43 fcOut.close();
44 in.close();
45 out.close();
46 System.out.println("copy success");
47 }
48
49 /**
50 * 通过文件通道实现文件的复制
51 * @throws Exception
52 */
53 private static void copyFile() throws Exception{
54 //创建一个输入文件的通道
55 FileChannel fcIn = new FileInputStream("c:\\3D0.jpg").getChannel();
56 //创建一个输出文件的通道
57 FileChannel fcOut = new FileOutputStream("c:\\test\\3D0.jpg").getChannel();
58
59 ByteBuffer buf = ByteBuffer.allocate(1024);
60 while(fcIn.read(buf)!=-1){
61 buf.flip();
62 fcOut.write(buf);
63 buf.clear();
64 }
65 fcIn.close();
66 fcOut.close();
67 System.out.println("copy success.");
68 }
69
70 public static void main(String[] args) {
71 try {
72 // copyFile();
73 randomAccessFileCopy();
74 } catch (Exception e) {
75 // TODO Auto-generated catch block
76 e.printStackTrace();
77 }
78 }
79
80 }