当前位置:网站首页>使用 FileChannel 进行文件的复制拷贝
使用 FileChannel 进行文件的复制拷贝
2022-07-03 07:53:00 【雁迟】
package com.yanchi;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/** * @author yanchi * @date 2022/6/30 14:04 */
public class FileChannelTest {
public static void main(String[] args) {
try (
FileChannel from = new FileInputStream("data.txt").getChannel();
FileChannel to = new FileOutputStream("to.txt").getChannel();
) {
// 一次最高只能传输 2g
from.transferTo(0,from.size(),to);
} catch (IOException e) {
e.printStackTrace();
}
}
}
由于以上方法最大只能传输 2G 的文件,下面的代码对以上代码进行优化!!
package com.yanchi;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/** * @author yanchi * @date 2022/6/30 14:04 */
public class FileChannelTest {
public static void main(String[] args) {
try (
FileChannel from = new FileInputStream("data.txt").getChannel();
FileChannel to = new FileOutputStream("to.txt").getChannel();
) {
// 源文件字节数
long size = from.size();
// left 代表还剩下多少字节
for (long left = size; left > 0;){
left -= from.transferTo((size - left), left, to);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
边栏推荐
猜你喜欢

Go language foundation ----- 08 ----- interface

An article for you to understand - Manchester code

Screenshot tool snipaste

什么是数据类型?数据类型有什么用?

Iterm2 setting

Worldview satellite remote sensing image data / meter resolution remote sensing image

haproxy+keepalived搭建01

VMware virtual machine configuration static IP

Technical dry goods | Bert model for the migration of mindspore NLP model - text matching task (2): training and evaluation

Research shows that breast cancer cells are more likely to enter the blood when patients sleep
随机推荐
Go language - loop statement
[step on the pit series] MySQL failed to modify the root password
opensips与对方tls sip trunk对接注意事项
Differences between tp3.2 and tp5.0
PHP微信抢红包的算法
Go language foundation ----- 18 ----- collaboration security, mutex lock, read-write lock, anonymous lock, sync Once
Go language foundation ------ 12 ------ JSON
Go language foundation ----- 11 ----- regular expression
How to configure GDAL under idea
Pat class a 1031 Hello world for u
Technical dry goods | thinking about the unification of dynamic and static diagrams of AI framework
Pycharm remote ssh pyenv error: pydev debugger: warning: trying to add breakpoint to file that does
【MySQL 12】MySQL 8.0.18 重新初始化
Research shows that breast cancer cells are more likely to enter the blood when patients sleep
Go language foundation ----- 10 ----- string related operations (operation function, string conversion)
Oracle queries grouped by time
MAE
Screenshot tool snipaste
Iterm2 setting
Go language foundation ------ 14 ------ gotest