java 21

需求:复制图片
分析:
  因为图片我们用记事本打开后无法读懂,所以用字节流
  并且字节流复制有4种方式,所以我们尝试4种方式。
推荐第四种:缓冲字节流一次读取一个字节数组

首先写main方法:

 1 public static void main(String[] args) throws IOException {
 2         // 上次使用了字符串作为路径,这次我们使用File作为路径
 3         File start = new File("C:\Users\Administrator\Desktop\新建文件夹\艾斯.jpg");
 4         File end = new File("C:\Users\Administrator\Desktop\新建文件夹\火拳.jpg");
 5         //method1(start,end);
 6         //method2(start,end);
 7         //method3(start,end);
 8         method4(start,end);
 9 
10     }

第一种:基本字节流一次读取一个字节

 1     private static void method1(File start, File end) throws IOException {
 2         // 基本字节流一次读取一个字节
 3         FileInputStream fi = new FileInputStream(start);
 4         FileOutputStream fo = new FileOutputStream(end);
 5         int len = 0;
 6         while((len = fi.read()) != -1){
 7             fo.write(len);
 8         }
 9         fi.close();
10         fo.close();
11         
12     }

第二种:基本字节流一次读取一个字节数组

 1     private static void method2(File start, File end) throws IOException {
 2         // 基本字节流一次读取一个字节数组
 3         FileInputStream fi = new FileInputStream(start);
 4         FileOutputStream fo = new FileOutputStream(end);
 5         byte[] by = new byte[1024];
 6         int len = 0;
 7         while((len = fi.read(by)) != -1){
 8             fo.write(by,0,len);
 9         }
10         fi.close();
11         fo.close();
12     }

第三种:缓冲字节流一次读取一个字节

 1     private static void method3(File start, File end) throws IOException {
 2         // 缓冲字节流一次读取一个字节
 3         BufferedInputStream bfi = new BufferedInputStream(new FileInputStream(start));
 4         BufferedOutputStream bfo  = new BufferedOutputStream(new FileOutputStream(end));
 5         int len = 0;
 6         while((len = bfi.read()) != -1){
 7             bfo.write(len);
 8         }
 9         bfi.close();
10         bfo.close();
11     }

第四种:缓冲字节流一次读取一个字节数组

 1     private static void method4(File start, File end) throws IOException {
 2         // 缓冲字节流一次读取一个字节数组
 3         BufferedInputStream bfi = new BufferedInputStream (new FileInputStream(start));
 4         BufferedOutputStream bfo = new BufferedOutputStream(new FileOutputStream(end));
 5         byte[] by = new byte[1024];
 6         int len = 0;
 7         while((len = bfi.read(by)) != -1){
 8             bfo.write(by,0,len);
 9         }
10         bfi.close();
11         bfo.close();
12         
13     }
何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5926455.html