基于【字节】操作的IO接口:InputStream、OutputStream

InputStream

1211163-20171009153027840-197402793.png

参考链接:对java中FileInputStream、BufferInputStream的理解

/**
 * Author:Mr.X
 * Date:2017/10/9 17:11
 * Description:
 * @read():一个一个字节的读(单字节读取)
 */
public class Demo1 {
    public static void main(String[] args) throws IOException{
        FileInputStream fis = new FileInputStream("e:/abc.txt");
        int by = 0;
        while ((by = fis.read()) != -1) {
            System.out.print((char) by);
        }
        fis.close();
    }
}

1211163-20171009172350918-1467244226.png

/**
 * Author:Mr.X
 * Date:2017/10/9 17:12
 * Description:
 *
 * @read(byte[] buf):先把字节存入到缓冲区字节数组中,一下读一个数组(常用)
 * @即(多字节读取)
 */
public class Demo2 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream(new File("e:/abc.txt"));
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = fis.read(buf)) != -1) {
            System.out.print(new String(buf, 0, len));
        }
        fis.close();
    }
}

1211163-20171009172421652-367152865.png

因为中文占用2Byte,英文占用1Byte,所以按照一个一个字节的读取得时,中文是要出问题的!
单个字节流只能操作英文,不能操作中文,所以要一次性读取多个字节才能读取中文信息!
abc.txt编码为uft-8,如果为其他编码的话,需要使用到字符流(专门用于操作字符)设置编码,不然中文会出问题!





OutputStream

1211163-20171009153541840-1127114878.png

参考链接:BufferedInputStream与BufferedOutputStream用法简介

public class Demo1 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("e:/b.txt");
        fos.write(65);
        fos.write(66);
        fos.write(67);
        fos.write(68);

        String str = " hello word!";
        fos.write(str.getBytes());
        fos.close();
    }
}

1211163-20171009204715434-1223772996.png

public class Demo2 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream(new File("e:/abc.txt"));
        FileOutputStream fos = new FileOutputStream("e:/b.txt");
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = fis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fos.close();
        fis.close();
    }
}

1211163-20171009204834324-549633585.png

转载于:https://www.cnblogs.com/bobi1234/p/7641303.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值