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

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

 

 

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

String类的构造

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

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

复制代码
public class Demo02InputStream {
    public static void main(String[] args) throws IOException {
        //创建FileInputStream对象,构造方法中绑定要读取的数据源
        FileInputStream fis = new FileInputStream("day09_IOAndProperties\\b.txt");
        //使用FileInputStream对象中的方法read读取文件
        //int read(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中。
        /*byte[] bytes = new byte[2];
        int len = fis.read(bytes);
        System.out.println(len);//2
        //System.out.println(Arrays.toString(bytes));//65,66
        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));//ED*/

        /*
            发现以上读取是一个吃哪个服的过程,可以使用循环优化
            不知道文件中有多少个字节,所以使用while循环
            while循环结束的条件,读取到-1结束
        */
        byte[] bytes = new byte[1024];
        int len = 0; //记录每次读取的有效字节个数
        while ((len = fis.read(bytes)) != -1){
            //String(byte[] bytes,int offset,int length) 把字节数组的一部分转换为字符串 offset:数组的开始索引 length:转换的字节个数
            System.out.println(new String(bytes,0,len));
        }
        //释放资源
        fis.close();
    }
}
复制代码

 

 

 

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