Java学习-IO流-文件拷贝练习
FileInputStream fis = new FileInputStream("...\\xx.mp4");
FileOutputStream fos = new FileOutputStream("...\\copy.mp4");
int b;
//边读边写
while((b=fis.read())!=-1){
fos.write()b;
}
fos.close();//后开的资源先释放
fis.close();
思考: 如果拷贝的文件过大,速度会不会有影响?
原因: FileInputStream一次读写一个字节
FileInputStream 一次读取多个字节
public int read(byte[] buffer)//一次读一个字节数组数据
一次读一个字节数组的数据,每次读取会尽可能把数组装满
数组越大,读取越快,但数组也占用内存空间,如果数组长度过大,内存可能直接崩掉
案例:
xx.txt:abcde
FileInputStream fis = new FileInputStream("...\\xx.txt");
byte[] bytes = new byte[2];
int len1 = fis.read(bytes);
sout(len1);//→ 2
String str1 = new String(bytes);
sout(str1);// ab
int len2 = fis.read(bytes);
sout(len2);//→ 2
String str2 = new String(bytes);
sout(str2);// cd
int len3 = fis.read(bytes);
sout(len3);//→ 1
String str3 = new String(bytes);
sout(str3);// ed
int len4 = fis.read(bytes);
sout(len4);//→ -1
String str4 = new String(bytes);
sout(str4);// ed
fis.close();
FileInputStream 一次读多个字节
xx.txt:abcde
1.int len:记录当前读了多少个数据
2.byte[] bytes:读取到的数据
3.len1 = fis.read(bytes):把读取到的数据装到 bytes 数组中,每次尽可能把数组装满,第一次读到两个:ab
4.len2 = fis.read(bytes):读入 cd,存入 bytes,原有的 ab 被覆盖
5.len3 = fis.read(bytes):读入e,存入 bytes,原有的 c 被覆盖,但 d 没有被覆盖,数组中的数据为 ed
6.len4 = fis.read(bytes):没有读到数据,read() 返回 -1,数组中的数据依然是 ed
7.如果在 len3 需要覆盖 d,需要在 String() 中加入两个参数,表示存入的起始位置和终止位置
len3 = fis.read(bytes);
sout(new String(bytes,0,len3));//→ e
文件拷贝案例改写
FileInputStream fis = new FileInputStream("...\\xx.mp4");
FileOutputStream fos = new FileOutputStream("...\\copy.mp4");
int len;
byte[] bytes = new byte[1024*1024*5];
while((len = fis.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fos.close();
fis.close();