在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java 使用NIO进行快速的文件拷贝的代码

2016-12-20 13:15| 发布者: zhangjf| 查看: 454| 评论: 0

摘要: public static void fileCopy( File in, File out ) throws IOException { FileChannel inChannel = new FileInputStream( in ).getChannel(); FileChannel outChannel = new FileOutputStream( out ).getCh ...
  1. public static void fileCopy( File in, File out ) throws IOException
  2. {
  3. FileChannel inChannel = new FileInputStream( in ).getChannel();
  4. FileChannel outChannel = new FileOutputStream( out ).getChannel();
  5. try
  6. {
  7. inChannel.transferTo(0, inChannel.size(), outChannel);
  8. // original -- apparently has trouble copying large files on Windows
  9. // magic number for Windows, 64Mb - 32Kb)
  10. int maxCount = (64 * 1024 * 1024) - (32 * 1024);
  11. long size = inChannel.size();
  12. long position = 0;
  13. while ( position < size )
  14. {
  15. position += inChannel.transferTo( position, maxCount, outChannel );
  16. }
  17. }
  18. finally
  19. {
  20. if ( inChannel != null )
  21. {
  22. inChannel.close();
  23. }
  24. if ( outChannel != null )
  25. {
  26. outChannel.close();
  27. }
  28. }
  29. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 08:05

Copyright 2015-2025 djqfx

返回顶部