导航

Java经典代码片段——使用NIO进行快速的文件拷贝

Posted on 2017-07-02 16:16  天一涯  阅读(218)  评论(0编辑  收藏  举报
 1     public static void fileCopy(File in, File out) throws IOException {
 2         FileChannel inChannel = new FileInputStream(in).getChannel();
 3         FileChannel outChannel = new FileOutputStream(out).getChannel();
 4         try {
 5             // inChannel.transferTo(0, inChannel.size(), outChannel); //
 6             // original – apparently has trouble copying large files on Windows
 7             // magic number for Windows, 64Mb - 32Kb)
 8             int maxCount = (64 * 1024 * 1024) - (32 * 1024);
 9             long size = inChannel.size();
10             long position = 0;
11             while (position < size) {
12                 position += inChannel
13                         .transferTo(position, maxCount, outChannel);
14             }
15         } finally {
16             if (inChannel != null) {
17                 inChannel.close();
18             }
19             if (outChannel != null) {
20                 outChannel.close();
21             }
22         }
23     }