IO series one: conversion of input and output streams

The principle of input stream to byte array: 

1. Read the input stream, read each small segment once, and take out the byteArray.
2. Write the small segment of byteArray to the byte output stream ByteOutStream. until no more bytes can be read from the input stream.
3. Convert the byte output stream into a byte array.

Source code:

public class ByteToInputStream {  
  
    public static final InputStream byte2Input(byte[] buf) {  
        return new ByteArrayInputStream(buf);  
    }  
  
    public static final byte[] input2byte(InputStream inStream)  
            throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[100];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 100)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    }  
  
}

Question 1: Why does the input stream need to be read in small sections instead of the whole section?
Answer: If you need to read the entire segment, you need to take the available() of the input stream, but this method cannot correctly return the total length of the input stream.

Question 2: Why can't the available() of the input stream return the total length? 
Answer: You need to view the source code of the available method.








Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324660720&siteId=291194637