Java 输入流read()返回的int值。什么时候是-1,什么时候是读取到byte[]的数据个数

1加缓冲区,返回的是数据个数,读取完返回-1

public class MyClass {
    
    
    public static void main(String[] args)  throws IOException{
    
    
        FileInputStream inputStream;
         File file=new File("D:\\bg.txt");
        try {
    
    
            inputStream=new FileInputStream(file);
            byte[] b=new byte[1024];
            int d;
            while ((d=inputStream.read(b))!=-1){
    
    
                System.out.println(d);//输出 12
            }
            System.out.println("+**"+d);//输出 -1
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            if (inputStream!=null){
    
    
                inputStream.close();
            }
        }
    }
}

2不加缓冲区,返回的是一个字节,读取完返回-1

public class MyClass {
    
    
    public static void main(String[] args)  throws IOException{
    
    
        FileInputStream inputStream;
         File file=new File("D:\\bg.txt");
        try {
    
    
            inputStream=new FileInputStream(file);
            int d;
            while ((d=inputStream.read())!=-1){
    
    
                System.out.println(d);
                /*  输出
                  230
                  137
                  147
                  229
                  188
                  128
                  231
                  156
                  139
                  231
                  156
                  139
                */
            }
            System.out.println("+**"+d);//输出 -1
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            if (inputStream!=null){
    
    
                inputStream.close();
            }
        }
    }
}

Java 小白 学习笔记,有问题还请指导

猜你喜欢

转载自blog.csdn.net/LiuxXn/article/details/103629478