1. 程式人生 > >InputStream轉換為String, byte[] data = new byte[1024]詳解

InputStream轉換為String, byte[] data = new byte[1024]詳解

() gpo ring copyright create import number rgs write

/**
 * This file created at 2018年2月28日.
 *
 * Copyright (c) 2002-2018 Bingosoft, Inc. All rights reserved.
 */
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * <code>{
@link ByteTest}</code> * * TODO : document me * * @author ke */ public class ByteTest { public static void main(String[] args) { String inputStr = "hello123456"; String outputStr = ""; try { InputStream inputStream = new ByteArrayInputStream(inputStr.getBytes("UTF-8")); //
/這裏需要用try...catch...不然報錯 // ByteArrayInputStream:ByteArrayInputStream(byte[] buf) // 創建一個 ByteArrayInputStream,使用 buf 作為其緩沖區數組。 // String:byte[] getBytes(Charset charset) // 使用給定的 charset 將此 String 編碼到 byte 序列,並將結果存儲到新的 byte 數組。 outputStr = changeInputStream(inputStream, "utf-8"); System.out.println(outputStr); }
catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public static String changeInputStream(InputStream inputStream, String encode) { String res = ""; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // byte[] data = new byte[100];///輸出 hello123456 byte[] data = new byte[5];///每次讀取5個字節 int len = 0; try { while ((len = inputStream.read(data)) != -1) { ////inputStream-->data[] // InputStream: int read(byte[] b) // 從輸入流中讀取一定數量的字節,並將其存儲在緩沖區數組 b 中。 // 返回: // 讀入緩沖區的總字節數;如果因為已經到達流末尾而不再有數據可用,則返回 -1。 outputStream.write(data, 0, len);/////outputStream<--data[] // ByteArrayOutputStream: void write(byte[] b, int off, int len) // 將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此 byte 數組輸出流。 } res = new String(outputStream.toByteArray(), encode); // ByteArrayOutputStream: byte[] toByteArray() // 創建一個新分配的 byte 數組。 // String: String(byte[] bytes, Charset charset) // 通過使用指定的 charset 解碼指定的 byte 數組,構造一個新的 String。 inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return res; }//changeInputStream }

我最想說明的是,雖然data[]的長度比string短,但仍然也會輸出string的所有字符,不會只輸出data[]的長度的字符串

第一次取前5個字符寫入outputStream中,往後都是每次寫入5個字符到outputStream中,直到寫入到字符串末尾

InputStream轉換為String, byte[] data = new byte[1024]詳解