字节输入流一次读取—个字节的原理以及字节输入流—次读取多个字节

字节输入流一次读取—个字节的原理

 

 

 

 

 

 

 

 

 

 

 

 

字节输入流—次读取多个字节

int read(byte[] b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中。

明确两件事情:
  1.方法的参数byte[]的作用?
    起到缓冲作用,存储每次读取到的多个字节
    数组的长度一般定义为1024(1kb)或者1024的整数倍
  2.方法的返回值int是什么?
    每次读取的有效字节个数

String类的构造方法

String(byte[] bytes):把字节数组转换为字符串

String(byte[] bytes,int offset,int length)把字节数组的一部分转换为字符串.offset:数组的开始索引 length:转换的字节个数

 

复制代码
    public static void main(String[] args) throws IOException {
        //1.创建FileInputStream对象,构造方法中绑定要读取的数据源
        FileInputStream fis = new FileInputStream("G:\\44.txt");
        //2.使用FileInputStream对象中的方法read,读取文件
        byte[] bytes = new byte[2];
        int len = fis.read(bytes);
        System.out.println(len);//2
        System.out.println(new String(bytes));//AB

        len = fis.read(bytes);
        System.out.println(len);//2
        System.out.println(new String(bytes));//CD

        len = fis.read(bytes);
        System.out.println(len);//1
        System.out.println(new String(bytes));//ED

        len = fis.read(bytes);
        System.out.println(len);//-1
        System.out.println(new String(bytes));
        //3.释放资源
        fis.close();
    }
复制代码

 

 

posted @   xjw12345  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示