1 import java.io.*; 2 3 public class FileCopy { 4 public static void main(String[] args) { 5 Copy("女子.jpg", "漂亮.jpg"); 6 } 7 public static void Copy(String srcPath, String destPath) { 8 //1、创建源 9 File src = new File(srcPath); //源头 10 File dest = new File(destPath); //目的地 11 //2、选择流 12 InputStream inputStream = null; 13 OutputStream outputStream = null; 14 try { 15 inputStream = new FileInputStream(src); 16 outputStream = new FileOutputStream(dest); 17 //3、操作流(分段读取) 18 byte[] flush = new byte[1024]; //缓冲容器 19 int len = -1;//接收长度 20 while ((len = inputStream.read(flush)) != -1) { 21 outputStream.write(flush, 0, len); 22 } 23 outputStream.flush();//刷新此输出流并强制任何缓冲的输出字节被写出,细节 24 } catch (FileNotFoundException e) { 25 e.printStackTrace(); 26 } catch (IOException e) { 27 e.printStackTrace(); 28 } finally { 29 //4、释放资源,分别关闭,先打开的后关闭, 好处:只要保证我的目的地正确就可以 30 try { 31 if (outputStream != null) { 32 outputStream.close(); 33 } 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } 37 38 try { 39 if (inputStream != null) { 40 inputStream.close(); 41 } 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } 45 } 46 } 47 }