java拷贝文件
2019-04-17 / JAVA / 1018 次围观 / 0 次吐槽 /这种方式开发中建议经常使用
拷由文件时应该使用缓冲区思想、或者杯子思想
缓冲区思想、杯子思想是指把文件数据先读取到一个字节数组中【byte buf[]】,然后再把字节数组中的数据写入文件中
字节流一次读写一个数组的速度明显比一次读写一个字节的速度快很多
public class Demo01 {
public static void main(String[] args) throws IOException {
//案例:拷贝
/**
* 1.每次只读一个字节,又觉得太慢
* 2.一次性读一个文件的所有数据,又怕内存装不下
* 内存只有2G,视频3G,这样就会内存溢出
*
* 3.最终解决方法:折中,定义每次读8KB
*
*/
//1.输入流
FileInputStream fis = new FileInputStream("C:/Users/10301/Desktop/a/cm.jpg");
//2.输出流
FileOutputStream fos = new FileOutputStream("C:/Users/10301/Desktop/a/cm-副本2.jpg");
//3.定义个8kb字节数组,也叫缓冲区流
byte[] bytes = new byte[1024 * 8];
int len = 0;
int i = 0;
while( (len = fis.read(bytes)) != -1){
i++;
//4.写入文件
fos.write(bytes,0,len);
}
System.out.println("读取的次数:" + i);
//5.关闭流
fis.close();
fos.close();
}
}- 上一篇:递归
- 下一篇:Linux更改网卡为全双工模式
Powered By Cheug's Blog
Copyright Cheug Rights Reserved.