IO字节流文件复制
1 public static void main(String[] args) { 2 InputStream is = null; 3 OutputStream os = null; 4 try { 5 // 源文件 6 is = new FileInputStream("F:\\Pictures\\夏豆4k+2k+mp4\\夏豆被画脸2 4k.jpg"); 7 // InputStream is = new FileInputStream("D:\\WorkSpace\\code\\basic-app\\src\\outInputStream.txt"); 8 // 目标地址 9 os = new FileOutputStream("D:\\WorkSpace\\code\\basic-app\\src\\xd.jpg"); 10 // OutputStream os = new FileOutputStream("D:\\WorkSpace\\code\\basic-app\\src\\test.txt"); 11 12 // 定义一个数组转移数据 13 byte[] bytes = new byte[1024]; 14 // 记录每次的字节数 15 int len; 16 while ((len = is.read(bytes)) != -1){ 17 os.write(bytes, 0,len); 18 } 19 System.out.println("复制完成~~~"); 20 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } finally { 24 25 // 开发中不建议在此用 return 否则数据会出差,不管上边结果如何、都只会返回这里的 return 数据 26 27 // 关闭资源 28 try { 29 os.close(); 30 } catch (IOException e) { 31 throw new RuntimeException(e); 32 } 33 try { 34 is.close(); 35 } catch (IOException e) { 36 throw new RuntimeException(e); 37 } 38 } 39 }
1 public static void main(String[] args) { 2 try( 3 // 此位置只能放资源对象,用完自动关闭资源。 4 // 源文件 5 InputStream is = new FileInputStream("F:\\Pictures\\夏豆4k+2k+mp4\\夏豆被画脸2 4k.jpg"); 6 // InputStream is = new FileInputStream("D:\\WorkSpace\\code\\basic-app\\src\\outInputStream.txt"); 7 // 目标地址 8 OutputStream os = new FileOutputStream("D:\\WorkSpace\\code\\basic-app\\src\\xd.jpg"); 9 // OutputStream os = new FileOutputStream("D:\\WorkSpace\\code\\basic-app\\src\\test.txt"); 10 ) { 11 // 定义一个数组转移数据 12 byte[] bytes = new byte[1024]; 13 // 记录每次的字节数 14 int len; 15 while ((len = is.read(bytes)) != -1){ 16 os.write(bytes, 0,len); 17 } 18 System.out.println("复制完成~~~"); 19 20 } catch (Exception e) { 21 e.printStackTrace(); 22 } 23 }