package com.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//代码胜千言
public class Demo5 {
public static void main(String[] args) throws IOException, InterruptedException {
//指定输入
File inputFile = new File("E:"+File.separator+"z.jpg");
//创建FileInputStream输入流对象。
FileInputStream fileInputStream = new FileInputStream(inputFile);
//指定输出
File outPutFile = new File("F:"+File.separator+"a.jpg");
//创建FileOutputStream输出流对象。
FileOutputStream fileOutputStream= new FileOutputStream(outPutFile);
//创建缓冲字符流--存储读取到的数据 缓冲数组 的长度一般是1024的倍数,因为与计算机的处理单位。 理论上缓冲数组越大,效率越高
byte[] filebyte = new byte[1024];
保存每次读取到的字节个数。
int length=0;
//read()!=-1时,写入字节
while((length=fileInputStream.read(filebyte))!=-1){
//输出字节
fileOutputStream.write(filebyte,0,length);
}
//关闭资源---先开后关,后开先关
fileOutputStream.close();
fileInputStream.close();
}
}
异常处理
package com.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo6 {
public static void CopyImage(){
File inputFile = new File("E:"+File.separator+"z.jpg");
File outPutFile = new File("F:"+File.separator+"a.jpg");
FileInputStream fileInputStream=null;
FileOutputStream fileOutputStream=null;
try{
fileInputStream = new FileInputStream(inputFile);
fileOutputStream= new FileOutputStream(outPutFile);
byte[] filebyte = new byte[1024];
int length=0;
while((length=fileInputStream.read(filebyte))!=-1){
fileOutputStream.write(filebyte,0,length);
}
}catch (Exception e) {
System.out.println("拷贝图片失败.....");
throw new RuntimeException(e);
}finally{
try {
if(fileOutputStream!=null){
fileOutputStream.close();
System.out.println("关闭输出流成功....");
}
} catch (IOException e) {
System.out.println("关闭输出流失败....");
throw new RuntimeException(e);
}
try {
if(fileInputStream!=null){
fileInputStream.close();
System.out.println("关闭输入流成功....");
}
} catch (IOException e) {
System.out.println("关闭输入流失败....");
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
CopyImage();
}
}