Java IO: ByteArrayOutputStream使用


感謝原文作者:小思思smile
原文鏈接:https://blog.csdn.net/u014049880/article/details/52329333/
更多請查閱Java API文檔!

在創建ByteArrayOutputStream類實例時,內存中會創建一個byte數組類型的緩沖區,緩沖區會隨着數據的不斷寫入而自動增長

可使用toByteArray()toString()獲取數據。

關閉ByteArrayOutputStream無效,此類中的方法在關閉此流后仍可被調用,而不會產生任何IOException
在網絡傳輸中我們往往要傳輸很多變量,我們可以利用ByteArrayOutputStream把所有的變量收集到一起,然后一次性把數據發送出去

示例

示例一:

public static void main(String[] args) { 
    int a = 0; 
    int b = 1; 
    int c = 2; 
    ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
    bout.write(a); 
    bout.write(b); 
    bout.write(c); 
    byte[] buff = bout.toByteArray(); 
    for (int i = 0; i < buff.length; i++) 
        System.out.println(buff[i]); 
    System.out.println("***********************"); 
    ByteArrayInputStream bin = new ByteArrayInputStream(buff); 
    while ((b = bin.read()) != -1) { 
        System.out.println(b); 
    } 
}

示例二:

	/** * 讀取文件內容 * * @param filename 文件名 * @return */
	public String read(String filename) throws Exception
	{
		FileInputStream fis = new.FileInputStream(filename); 
		ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
		byte[] buffer = new byte[1024];
		int len = 0;
		// 將內容讀到buffer中,讀到末尾為-1
		while ((len = fis.read(buffer)) != -1)
		{
			// 本例子將每次讀到字節數組(buffer變量)內容寫到內存緩沖區中,起到保存每次內容的作用
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray(); // 取內存中保存的數據
		fis.close();
		String result = new String(data, "UTF-8");
		return result;
	}

我的項目實際使用

倉庫地址:https://github.com/b84955189/TF-MIS
源路徑:src/main/java/utils/CommonUtils.java


    /** * 將輸入流轉為字節數組 * @author Jason * @date 9:49 AM 6/19/2020 * @param * @return */
    public static byte[] toByteArray(InputStream in) throws IOException {
        ByteOutputStream byteOutputStream = new ByteOutputStream();
        byte[] bytes = new byte[1024];
        int len=0;
        while ((len=in.read(bytes))!=-1){
             byteOutputStream.write(bytes,0,len);
        }
        return  byteOutputStream.toByteArray();
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM