Java实现文件拷贝

简介:

经过一组简单的测试发现JAVA NIO提供的文件内存映射方法实现文件拷贝速度最快,不管是大文件还是小文件,特别是大文件的拷贝速度比普通方法提高20倍,唯一有个前提就是内存需要足够大,否则文件映射肯定失败(当然可以通过分割文件,部分映射的方法避免,但就比较麻烦了);其次NIO提供的文件管道传输速度也比较好,如果没法做文件内存映射,推荐这种拷贝方法;另外,Buffer的大小,对于读写速度还是有影响的,基本就是Buffer越大读写越快(有个疑问就是Buffer.allocateDirec()效率提高不明显);最后,总体看来NIO的效率比老IO高,不管使用哪种方式,老IO使用流读写只能一个字节一个字节的抠,NIO使用块的方式读写还是相对比较快,所以没有特别需求的情况下,推荐使用NIO,目前NIO基本能覆盖老IO的所有功能(当然NIO还提供N多新功能)。


  • 测试环境

1
2
3
4
5
6
7
8
9
Eclipse(Juno) JVM(Sun JDK1. 7 ) 参数:
-Xms1536m
-Xmx1536m
-Xverify:none -XX:+UseParallelGC
-XX:PermSize=128M
-XX:MaxPermSize=128M
OS参数:
Win7 64Bit + 4GB
物理磁盘空间充足


  • 测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import  java.io.FileInputStream;
import  java.io.FileNotFoundException;
import  java.io.FileOutputStream;
import  java.io.IOException;
import  java.io.RandomAccessFile;
import  java.nio.ByteBuffer;
import  java.nio.MappedByteBuffer;
import  java.nio.channels.FileChannel;
public  class  FileCopy {
     private  static  final  int  BUFFER_SIZE_1024 =  1024 ;
     private  static  final  int  BUFFER_SIZE_4096 =  4096 ;
     private  static  final  int  BUFFER_SIZE_10240 =  10240 ;
        
     private  static  final  String FROM_FILE_42MB =  "G:/from_42MB.rar" ;
     private  static  final  String FROM_FILE_1GB =  "G:/from_350MB.rar" ;
        
     private  static  int  BUFFER_SIZE = BUFFER_SIZE_1024;
     private  static  String FROM_FILE = FROM_FILE_42MB;
     /**
      * @param args
      * @throws Exception
      */
     public  static  void  main(String[] args)  throws  Exception {
         System.out.println( "File :"  + FROM_FILE +  " ---- Buffer Size : "  + BUFFER_SIZE +  "--------------" );
         testFileCopy();
            
         BUFFER_SIZE = BUFFER_SIZE_4096;
         System.out.println( "File :"  + FROM_FILE +  " ---- Buffer Size : "  + BUFFER_SIZE +  "--------------" );
         testFileCopy();
            
         BUFFER_SIZE = BUFFER_SIZE_10240;
         System.out.println( "File :"  + FROM_FILE +  " ---- Buffer Size : "  + BUFFER_SIZE +  "--------------" );
         testFileCopy();
            
         BUFFER_SIZE = BUFFER_SIZE_1024;
         FROM_FILE = FROM_FILE_1GB;
         System.out.println( "File :"  + FROM_FILE +  " ---- Buffer Size : "  + BUFFER_SIZE +  "--------------" );
         testFileCopy();
            
         BUFFER_SIZE = BUFFER_SIZE_4096;
         FROM_FILE = FROM_FILE_1GB;
         System.out.println( "File :"  + FROM_FILE +  " ---- Buffer Size : "  + BUFFER_SIZE +  "--------------" );
         testFileCopy();
            
         BUFFER_SIZE = BUFFER_SIZE_10240;
         FROM_FILE = FROM_FILE_1GB;
         System.out.println( "File :"  + FROM_FILE +  " ---- Buffer Size : "  + BUFFER_SIZE +  "--------------" );
         testFileCopy();
            
     }
     private  static  void  testFileCopy()  throws  FileNotFoundException,
             IOException {
         coypByMbb();
         copyByNioTransferFrom();
         copyByNioTransferTo();
         coypByBufferRead();
         coypByFastBufferRead();           
         coypByStream(); //Old IO style
     }
     /**
      * 使用FileChannel.transferFrom()实现
      * @throws FileNotFoundException
      * @throws IOException
      */
     private  static  void  copyByNioTransferFrom()  throws  FileNotFoundException,
             IOException {
         long  startTime = System.currentTimeMillis();
         RandomAccessFile fromFile =  new  RandomAccessFile(FROM_FILE,  "rw" );
         FileChannel fromChannel = fromFile.getChannel();
         RandomAccessFile toFile =  new  RandomAccessFile( "G:/to1.rar" ,  "rw" );
         FileChannel toChannel = toFile.getChannel();
         long  position =  0 ;
         long  count = fromChannel.size();
         toChannel.transferFrom(fromChannel, position, count);
         long  endTime = System.currentTimeMillis();
         System.out.println( "copyByNioTransferFrom time consumed(buffer size no effect) : "
                 + (endTime - startTime));
     }
     /**
      * 使用FileChannel.transferTo()实现
      * @throws FileNotFoundException
      * @throws IOException
      */
     private  static  void  copyByNioTransferTo()  throws  FileNotFoundException,
             IOException {
         long  startTime = System.currentTimeMillis();
         RandomAccessFile fromFile =  new  RandomAccessFile(FROM_FILE,  "rw" );
         FileChannel fromChannel = fromFile.getChannel();
         RandomAccessFile toFile =  new  RandomAccessFile( "G:/to2.rar" ,  "rw" );
         FileChannel toChannel = toFile.getChannel();
         long  position =  0 ;
         long  count = fromChannel.size();
         fromChannel.transferTo(position, count, toChannel);
         long  endTime = System.currentTimeMillis();
         System.out.println( "copyByNioTransferTo time consumed(buffer size no effect) : "
                 + (endTime - startTime));
     }
     /**
      * 使用Channel, Buffer简单读写实现
      * @throws IOException
      */
     private  static  void  coypByBufferRead()  throws  IOException {
         long  startTime = System.currentTimeMillis();
         FileInputStream fin =  new  FileInputStream(FROM_FILE);
         FileOutputStream fout =  new  FileOutputStream( "G:/to3.rar" );
         FileChannel fcin = fin.getChannel();
         FileChannel fcout = fout.getChannel();
         ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
         while  ( true ) {
             buffer.clear();
             int  r = fcin.read(buffer);
             if  (r == - 1 ) {
                 break ;
             }
             buffer.flip();
             fcout.write(buffer);
         }
         long  endTime = System.currentTimeMillis();
         System.out.println( "coypByBufferRead time consumed(buffer size take effect) : "
                 + (endTime - startTime));
     }
     /**
      * 使用连续内存的Buffer实现
      * @throws IOException
      */
     private  static  void  coypByFastBufferRead()  throws  IOException {
         long  startTime = System.currentTimeMillis();
         FileInputStream fin =  new  FileInputStream(FROM_FILE);
         FileOutputStream fout =  new  FileOutputStream( "G:/to4.rar" );
         FileChannel fcin = fin.getChannel();
         FileChannel fcout = fout.getChannel();
         ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
         while  ( true ) {
             buffer.clear();
             int  r = fcin.read(buffer);
             if  (r == - 1 ) {
                 break ;
             }
             buffer.flip();
             fcout.write(buffer);
         }
         long  endTime = System.currentTimeMillis();
         System.out.println( "coypByFastBufferRead time consumed(buffer size take effect) : "
                 + (endTime - startTime));
     }
     /**
      * 使用文件内存映射实现
      * @throws IOException
      */
     private  static  void  coypByMbb()  throws  IOException {
         long  startTime = System.currentTimeMillis();
         FileInputStream fin =  new  FileInputStream(FROM_FILE);
         RandomAccessFile fout =  new  RandomAccessFile( "G:/to5.rar" ,  "rw" );
         FileChannel fcin = fin.getChannel();
         FileChannel fcout = fout.getChannel();
         MappedByteBuffer mbbi = fcin.map(FileChannel.MapMode.READ_ONLY,  0 ,
                 fcin.size());
         MappedByteBuffer mbbo = fcout.map(FileChannel.MapMode.READ_WRITE,  0 ,
                 fcin.size());
         mbbo.put(mbbi);
         mbbi.clear();
         mbbo.clear();
         long  endTime = System.currentTimeMillis();
         System.out
                 .println( "coypByMbb time consumed(buffer size no effect) : "  + (endTime - startTime));
     }
     /**
      * 使用传统IO的流读写方式实现
      * @throws IOException
      */
     private  static  void  coypByStream()  throws  IOException {
         long  startTime = System.currentTimeMillis();
         FileInputStream fin =  new  FileInputStream(FROM_FILE);
         FileOutputStream fout =  new  FileOutputStream( "G:/to6.rar" );
         byte [] buffer =  new  byte [BUFFER_SIZE];
         while  ( true ) {
             int  ins = fin.read(buffer);
             if  (ins == - 1 ) {
                 fin.close();
                 fout.flush();
                 fout.close();
                 break ;
             }  else {
                 fout.write(buffer,  0 , ins);
             }             
         }
         long  endTime = System.currentTimeMillis();
         System.out.println( "coypByStream time consumed(buffer size take effect) : "  + (endTime - startTime));
     }
}
  • 测试结果

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    File :G:/from_42MB.rar ---- Buffer Size :  1024 --------------
    coypByMbb time consumed(buffer size no effect) :  47
    copyByNioTransferFrom time consumed(buffer size no effect) :  62
    copyByNioTransferTo time consumed(buffer size no effect) :  47
    coypByBufferRead time consumed(buffer size take effect) :  249
    coypByFastBufferRead time consumed(buffer size take effect) :  188
    coypByStream time consumed(buffer size take effect) :  187
              
    File :G:/from_42MB.rar ---- Buffer Size :  4096 --------------
    coypByMbb time consumed(buffer size no effect) :  15
    copyByNioTransferFrom time consumed(buffer size no effect) :  16
    copyByNioTransferTo time consumed(buffer size no effect) :  31
    coypByBufferRead time consumed(buffer size take effect) :  125
    coypByFastBufferRead time consumed(buffer size take effect) :  79
    coypByStream time consumed(buffer size take effect) :  93
              
    File :G:/from_42MB.rar ---- Buffer Size :  10240 --------------
    coypByMbb time consumed(buffer size no effect) :  16
    copyByNioTransferFrom time consumed(buffer size no effect) :  32
    copyByNioTransferTo time consumed(buffer size no effect) :  31
    coypByBufferRead time consumed(buffer size take effect) :  78
    coypByFastBufferRead time consumed(buffer size take effect) :  62
    coypByStream time consumed(buffer size take effect) :  63
              
    File :G:/from_350MB.rar ---- Buffer Size :  1024 --------------
    coypByMbb time consumed(buffer size no effect) :  280
    copyByNioTransferFrom time consumed(buffer size no effect) :  453
    copyByNioTransferTo time consumed(buffer size no effect) :  7785
    coypByBufferRead time consumed(buffer size take effect) :  8144
    coypByFastBufferRead time consumed(buffer size take effect) :  7068
    coypByStream time consumed(buffer size take effect) :  8503
              
    File :G:/from_350MB.rar ---- Buffer Size :  4096 --------------
    coypByMbb time consumed(buffer size no effect) :  1904
    copyByNioTransferFrom time consumed(buffer size no effect) :  5978
    copyByNioTransferTo time consumed(buffer size no effect) :  7379
    coypByBufferRead time consumed(buffer size take effect) :  7621
    coypByFastBufferRead time consumed(buffer size take effect) :  7474
    coypByStream time consumed(buffer size take effect) :  8200
              
    File :G:/from_350MB.rar ---- Buffer Size :  10240 --------------
    coypByMbb time consumed(buffer size no effect) :  328
    copyByNioTransferFrom time consumed(buffer size no effect) :  6864
    copyByNioTransferTo time consumed(buffer size no effect) :  7021
    coypByBufferRead time consumed(buffer size take effect) :  7199
    coypByFastBufferRead time consumed(buffer size take effect) :  7941
    coypByStream time consumed(buffer size take effect) :  7801



     本文转自sarchitect 51CTO博客,原文链接:http://blog.51cto.com/stevex/1272956,如需转载请自行联系原作者




相关文章
|
Java
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
428 9
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
692 2
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
503 1
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
4350 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
690 14
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
1063 5
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
481 0
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
950 0
|
存储 算法 Java
解锁“分享文件”高效密码:探秘 Java 二叉搜索树算法
在信息爆炸的时代,文件分享至关重要。二叉搜索树(BST)以其高效的查找性能,为文件分享优化提供了新路径。本文聚焦Java环境下BST的应用,介绍其基础结构、实现示例及进阶优化。BST通过有序节点快速定位文件,结合自平衡树、多线程和权限管理,大幅提升文件分享效率与安全性。代码示例展示了文件插入与查找的基本操作,适用于大规模并发场景,确保分享过程流畅高效。掌握BST算法,助力文件分享创新发展。