FileInputStream和FileOutputStream实现照片的复制(一)

时间:2021-12-31 08:42:09
package cn.io;
//FileInputStream和FileOutputStream实现照片的复制(一)
//注意图片不可以用字符流(如FileReader和FileWriter)拷贝,因为它会去查找字符表
//在方式二中使用InputStream中的available()方法建立缓冲区
//这样操作的好处是不用循环操作,直接先全部暂存在一个数组里,然后再全部取出存到目的地
import java.io.*;
public class Test6 {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
System.out.println("……………………………以下为方式一………………………………");
fis=new FileInputStream("F:\\1.JPG");
fos=new FileOutputStream("F:\\2.JPG");
byte [] temp1=new byte[1024*1024];
int length=0;
while((length=fis.read(temp1))!=-1){
fos.write(temp1, 0, length);
fos.flush();
}
System.out.println("……………………………以下为方式二…………………………………");
fis=new FileInputStream("F:\\3.JPG");
fos=new FileOutputStream("F:\\4.JPG");
byte [] temp2=new byte[fis.available()];
fis.read(temp2);
fos.write(temp2);
} catch (Exception e) {
e.toString();
}
finally{
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.toString();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.toString();
}
}


}
}
}