1.InputSream抽像类与read()方法

InputStream类介绍

抽象类,子类FileInputStream

方法介绍

int read()、int read(byte[ ] b)、int read(byte[ ] b,int off,int len)

int read()

一次只读一个字节的数据,返回值是0~255的一个 int型整数,到最后没有可用字节时返回:-1

问题:读取一个字节,为什么不直接返回byte类型的数据?
答案:链接

代码示例

public static void main(String[] args) throws IOException {
        //File对象对文件或文件夹目录的抽象表示,与系统中某个文件或者文件夹建立连接
        //目录以及文件需要自己创建好
        File file = new File("C:\\Users\\Beshare\\Desktop\\demo\\test.txt");
        InputStream inputStream = new FileInputStream(file);

        //申明一个字节数组(用来保存读取到的数据)
        byte[] b = new byte[1024];

        int temp;
        int footer = 0;

        //一次只读一个字节
        while ((temp = inputStream.read()) != -1)
            b[footer++] = (byte)temp;
        String str = new String(b);

    }

int read(byte[ ] b)

从数据流读取一些字节并保存到缓冲数组b中,并返回缓冲区中数据的长度,如果没有数据了则返回:-1
代码

public static void main(String[] args) throws IOException {
        //文件目录及文件需要自己创建
        File file = new File("C:\\Users\\Beshare\\Desktop\\demo\\test.txt");
        //利用FileInputStream.read(byte b)来实现
        InputStream inputStream = new FileInputStream(file);
        //设置缓冲区
        byte[]b = new byte[2];

        StringBuilder stringBuilder= new StringBuilder();
        int length;
        while((length = inputStream.read(b)) !=-1) {
            stringBuilder.append(new String(b,0,length));
        }
        System.out.println(stringBuilder);
    }

int read(byte[ ] b,int off,int len)

从数据流读取一些字节并保存到缓冲数组b中(从坐标为off的地方存储,每次存的长度为len,并返回缓冲区中所存储的数据的长度(如果没有了则返回-1)
代码

public static void main(String[] args) throws IOException {
        //文件目录及文件需要自己创建
        File file = new File("C:\\Users\\Beshare\\Desktop\\demo\\test.txt");
        //利用FileInputStream.read(byte b)来实现
        InputStream inputStream = new FileInputStream(file);
        //设置缓冲区
        byte[]b = new byte[3];

        StringBuilder stringBuilder= new StringBuilder();
        int length;
        while((length = inputStream.read(b,1,2)) !=-1) {
            //上面的缓冲数组是从1开始的(off:1),则下面数组从1开始解码(offset:1)
            stringBuilder.append(new String(b,1,length));
        }
        System.out.println(stringBuilder);
    }

补充

构造器String(byte bytes[ ], int offset, int length ):
bytes: 要解码为字符的 byte
offset: 要解码的第一个 byte 的索引
length: 要解码的 byte 数 的长度
0:解码是 空格

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值