IO流实现文本复制以及图片复制

简言

回归字符流以及字节流时写的案例,使用字节流复制图片,使用字符流复制文本。缓冲流的底层也是用字节流或者字符流读写文件的,它本身并没有读写文件的能力,采用的是装饰器模式。在本文中就没有在写案例了。

代码

package com.hy.IOStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

/**
 * @author 谢英亮
 * @date 2018年1月5日 上午8:59:25
 * @Description: 图片以及文本复制
 */
public class Cope {
    public static void main(String[] args) throws IOException {
        // textCope();
        // imgCope();
    }

    /**
     * 字节流实现图片复制
     * 
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void imgCope() throws FileNotFoundException, IOException {

        InputStream is = new FileInputStream("src/com/hy/IOStream/mm.jpg");
        OutputStream os = new FileOutputStream("src/com/hy/IOStream/mm2.jpg");

        // 第一种方式

        byte[] b = new byte[is.available()];
        is.read(b, 0, b.length);
        os.write(b);

        // 第二种方式
        /*
         * byte[] b = new byte[1024]; 
         * while ((is.read(b, 0, b.length)) != -1) {
         * os.write(b); 
         * }
         */
        os.flush();
        os.close();
        is.close();
    }

    /**
     * 字符流实现文本复制
     * 
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void textCope() throws FileNotFoundException, IOException {
        Reader rd = new FileReader("src/com/hy/IOStream/text1.txt");
        Writer wt = new FileWriter("src/com/hy/IOStream/text2.txt");
        char[] cbuf = new char[1024];
        int len = 0;
        while ((len = rd.read(cbuf, 0, 1024)) != -1) {
            String str = new String(cbuf, 0, len);
            System.out.print(str);
            // 文本复制
            wt.write(cbuf, 0, len);
        }
        wt.flush();
        wt.close();
        rd.close();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值