io流字节输入流一次读取多个字节
字节输入流一次读取多个字节
字节输入流一次读取多个字节的方法:
int read(byte[] b)从输入流中读取一定数量的字节 并将其存储在缓冲区数字b中
明确两件事情:
1.方法的参数byte[]的作用
起到缓冲作用 存储每次读取到的多个字节
数组的长度一把定义为1024(1kb)或者1024的整数倍
2.方法的返回值int是什么
每次读取到有效字节个数
代码:
 public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("E:\\dest\\a.txt");
        //使用FileInputStream对象中的方法read读取文件
        byte[] bytes = new byte[2];
        int read = fis.read(bytes);
        System.out.println(bytes);
        System.out.println(read);
        System.out.println(Arrays.toString(bytes));
        System.out.println(new String(bytes));
        //关闭流释放资源
        fis.close();
    }
a.txt

运行结果:

执行流程图:

这里我们也可以使用while循环
代码:
public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("E:\\dest\\a.txt");
        //使用FileInputStream对象中的方法read读取文件
        byte[] bytes = new byte[1024];
        int len=0;
        while ((len=fis.read(bytes))!=-1){
            System.out.println(new String(bytes));
        }
        //关闭流释放资源
        fis.close();
    }
运行结果:

public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("E:\\dest\\a.txt");
        //使用FileInputStream对象中的方法read读取文件
        byte[] bytes = new byte[1024];
        int len=0;
        while ((len=fis.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }
        //关闭流释放资源
        fis.close();
    }
这样写可以防止数组位置浪费
运行结果:

 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号