zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java基础知识回顾之javaIO类---FileInputStream和FileOutputStream字节流复制图片

JAVA基础知识字节 图片 --- 复制 回顾 JavaIO
2023-09-14 08:57:14 时间
package com.lp.ecjtu;

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


/**
 * 
 * @author Administrator
 * 1.用字节读取流对象和图片相关联(输入流)
 * 2.用字节写入流对象创建一个图片文件。用于存储获取到的图片数据(输出流)
 * 3.通过循环读写,完成数据的储存
 * 4.关闭资源
 *
 */
public class CopyPicStream {

    /**
     * @param args
     */
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("d:\\1.jpg");//读取图像数据之类的原始字节流
            fos = new FileOutputStream("2.bmp");//用于写入诸如图像数据之类的原始字节流
            byte[] b = new byte[1024];
            int len = 0;
            while ((len=fis.read(b)) != -1){
                fos.write(b);
            }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            throw new RuntimeException("复制图片失败!");
        }finally{
            try {
                if(fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fos != null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}