1. 程式人生 > >IO流系列一:輸入輸出流的轉換

IO流系列一:輸入輸出流的轉換

pst 取出 nal block each bytearray puts write 為什麽

輸入流轉字節數組的原理
1、讀取輸入流,每一小段 讀一次,取出 byteArray 。
2、將該一小段byteArray寫入到字節輸出流ByteOutStream。直到不能從輸入流再讀出字節為止。
3、將字節輸出流轉成字節數組。

源碼:

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; } }

疑問1:為什麽輸入流,需要一小段一小段地讀,而不是整段讀取?
分析:如果需要整段讀取,則需要取輸入流的available(),但是該方法不能正確地返回輸入流的總長度。

疑問2:為什麽輸入流的available()不能返回總長度?
分析:查看available方法的源碼。返回值 描述是下面這個玩意,
* @return     an estimate of the number of bytes that can be read (or skipped
* over) from this input stream without blocking or {@code 0} when
* it reaches the end of the input stream.
大意就是 這個值是個估算的值,在讀取流的過程中,沒有發生阻塞時能夠讀取到的長度。
所以可以理解為在網絡中讀取時,可能會發生阻塞的情況。而在本地讀取時,則能保證流的不阻塞傳輸。
建議不使用該辦法獲取流的字節數組總長度。

IO流系列一:輸入輸出流的轉換