java输入输出12:IO流(拷贝图片)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yuming226/article/details/84201900
第1种实现方式
package filePackage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo8_FilePicture {
     
     public static void main(String[] args) throws IOException {
          FileInputStream fis = new FileInputStream("12.jpg");//创建输入流对象
          FileOutputStream fos = new FileOutputStream("copy.jpg");//创建输出流对象
          
          int b;
          while ((b = fis.read()) != -1) {//不断的读取每一个字节
              fos.write(b);//将每一个字节写出
          }
          
                            //关流释放资源
          fis.close();
          fos.close();
     }
}
第2种实现方式

字节数组拷贝之available()方法。

1、int read(byte[] b):一次读取一个字节数组,返回值为读取的字节个数。
2、write(byte[] b):一次写入一个字节数组。
3、available():获取读的文件所有的字节个数。

package filePackage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo9_Available {
     
     public static void main(String[] args) throws IOException {
          FileInputStream fis = new FileInputStream("12.jpg");
          FileOutputStream fos = new FileOutputStream("copy.jpg");
          
          int num = fis.available();//读取文件的字节数
          byte[] b = new byte[num];
          int n =fis.read(b);
          System.out.println(n);
          fos.write(b);
         
          fis.close();
          fos.close();
          
     }
}
第3种实现方式

定义小数组。

package filePackage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo10_ArrayCopy {
     
     public static void main(String[] args) throws IOException {
          FileInputStream fis = new FileInputStream("11.txt");
          FileOutputStream fos = new FileOutputStream("copy.txt");
          byte[] arr = new byte[2];
          int len;
          while ((len = fis.read(arr)) != -1) {
              fos.write(arr,0,len);
          }
          
          
          /*byte[] arr = new byte[2];
          
          int a = fis.read(arr);
          System.out.println(a);
          for (byte b : arr) {
              System.out.println(b);
          }
          
          System.out.println("----------------------------");
          
          a = fis.read(arr);
          System.out.println(a);
          for (byte b : arr) {
              System.out.println(b);
          }*/
          
          fis.close();
          fos.close();
     }
}

猜你喜欢

转载自blog.csdn.net/yuming226/article/details/84201900
今日推荐