java 图片和文字的复制

在这里插入代码片
    //将文件读取进来,并写入到另一个文件中。也就是完成复制的功能。
    public static void readWrite() {
        FileReader fr = null;
        FileWriter fw = null;

        try {
            File file1 = new File("dayio\\file\\b.txt");//读入文件对象
            File file2 = new File("dayio\\file\\d.txt");//写出文件对象 d文件不存在,可以帮我自动写入

            fr = new FileReader(file1);
            fw = new FileWriter(file2);

            //核心
            char[] cbuf = new char[5];//
            int len;//记录每次读取到cbuf的个数。
            while ((len = fr.read(cbuf)) != -1) {
                fw.write(cbuf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fr != null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fw != null)
                    fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //字节输入流  处理二进制 如:图片
    public static void streamPhoto()  {

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            File f1 = new File("C:\\Users\\Administrator\\Desktop\\photo\\a.png");
            File f2 = new File("C:\\Users\\Administrator\\Desktop\\photo\\b.png");//将图片复制到b中a

            FileInputStream fis = new FileInputStream(f1);
            FileOutputStream fos = new FileOutputStream(f2);

            //缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            byte[] cbsf = new byte[5];
            int len;
            while ((len = bis.read(cbsf)) != -1) {
                bos.write(cbsf, 0, len);// 将读取缓冲流文件 写入 输出缓冲流里,从0 开始,读取len那么长。
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
发布了7 篇原创文章 · 获赞 0 · 访问量 146

猜你喜欢

转载自blog.csdn.net/weixin_45812660/article/details/104997219