Java实现图片拷贝(使用FileInputStream、FileOutputStream)

文件拷贝:此次拷贝目标是一张图片

图片是二进制文件,所以采用字节流处理

目标:将D:/TestFile/1/rose.jpg拷贝到 D:/TestFile/2/下

思路:用FileInputStream和FileOutPutStream,一边读一边写,读完了也写完了(读一部分写一部分)

可以一次读一个字节,也可以一次读多个字节。

代码如下:

package filecopy;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件拷贝:拷贝一张图片
 * 图片是二进制文件,所以用字节流处理
 * 目标:将D:/TestFile/1/rose.jpg拷贝到 D:/TestFile/2/下
 * 思路:用FileInputStream和FileOutPutStream,一边读一边写,读完了也写完了(读一部分写一部分)
 */
public class FileCopy {
    public static void main(String[] args) {
        try {
            //第一种方式,用read(byte[] b) 和 write(byte[] b, int off, int len),一次读多个字节,这种效率高
            FileInputStream fileInputStream = new FileInputStream("D:/TestFile/1/rose.jpg");
            FileOutputStream fileOutputStream = new FileOutputStream("D:/TestFile/2/rose.jpg",true);
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(b)) != -1){
                //注意不能直接用write(b),因为读到最后是不满一个数组大小的,还按一个数组来写就会出错
                fileOutputStream.write(b,0,len);
            }
            System.out.println("图片拷贝成功!");

            //第二种方式 用read(int b) 和write(int b),一个字节一个字节读
            //因为上一次输入流读完已经到达了末尾,所以要再新开辟流
            FileInputStream fileInputStream2 = new FileInputStream("D:/TestFile/1/rose.jpg");
            FileOutputStream fileOutputStream2 = new FileOutputStream("D:/TestFile/2/rose2.jpg",true);
            int data = 0;
            while ((data = fileInputStream2.read()) != -1){
                fileOutputStream2.write(data);
            }
            System.out.println("梅开二度");

            fileInputStream.close();
            fileOutputStream.close();
            fileInputStream2.close();
            fileOutputStream2.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

你可能感兴趣的:(编程之路,java,开发语言)