File tree Expand file tree Collapse file tree
src/main/java/com/prd/io/nio Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1919 <dependencies >
2020 <dependency >
2121 <groupId >junit</groupId >
22+ <!-- JUnit入门-1.在IDEA创建JUnit测试用例 https://zhuanlan.zhihu.com/p/42453559-->
2223 <artifactId >junit</artifactId >
2324 <version >4.11</version >
24- <scope >test </scope >
25+ <scope >compile </scope > <!-- IDEA下maven工程找不到@Test https://blog.csdn.net/seudongnan/article/details/78268508 -- >
2526 </dependency >
2627 <dependency >
2728 <groupId >org.projectlombok</groupId >
Original file line number Diff line number Diff line change @@ -51,8 +51,13 @@ public void testNIOByTransferFrom() throws IOException {
5151 FileChannel inChannel = FileChannel .open (Paths .get ("E:\\ a.zip" ), StandardOpenOption .READ );
5252 FileChannel outChennel = FileChannel .open (Paths .get ("D:\\ b.zip" ),StandardOpenOption .WRITE ,
5353 StandardOpenOption .READ ,StandardOpenOption .CREATE_NEW );
54- outChennel .transferFrom (inChannel ,0 ,inChannel .size ());
54+ // outChennel.transferFrom(inChannel,0,inChannel.size());
5555
56+ // 加个while循环,保证全部数据都拷贝完成
57+ long transferred = 0 ; //已拷贝的字节数
58+ while (transferred !=inChannel .size ()) {
59+ transferred +=inChannel .transferTo (0 ,inChannel .size (),outChennel );
60+ }
5661 long end = System .currentTimeMillis ();
5762 // 复制文件所需的时间:29362
5863 System .out .println ("复制文件所需的时间:" + (end - startTime ));
@@ -108,7 +113,9 @@ public void testNIOByChannel()throws IOException {
108113 //将通道中的数据存入缓冲区
109114 while (inChannel .read (buf ) != -1 ) {
110115 buf .flip ();//切换读取数据的模式
111- outChanel .write (buf );
116+ while (buf .hasRemaining ()) {
117+ outChanel .write (buf );
118+ }
112119 buf .clear ();
113120 }
114121 outChanel .close ();
You can’t perform that action at this time.
0 commit comments