1. 程式人生 > >Java讀取InputStream長度,以及available、readAllBytes、read、mark、reset方法介紹

Java讀取InputStream長度,以及available、readAllBytes、read、mark、reset方法介紹

    /** 根據InputStream對應的位元組陣列讀取InputStream長度,會將InputStream指標移動至InputStream尾,不利於後續讀取,readInputStream(inputStream).length等同於inputStream.readAllBytes().length,readAllBytes從當前指標位置讀取,讀取後指標留在最後的位置 */

    public byte[] readInputStream(InputStream inputStream) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        try {
            while ((length = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return outStream.toByteArray();
    }
	
	/** 一步到位方式,從InputStream指標當前位置起獲取InputStream長度,且讀取後不會改動InputStream指標位置,沒有read指標從0開始 */
	inputStream.available();
	
    /** 擴充套件:從網路中讀取InputStream後,可能因網路質量一次讀取後InputStream長度為0,建議加入迴圈 */
	int count = 0; 
    while (count == 0) { 
    count = inputStream.available(); 
    }
  
    /** 擴充套件:如果已知InputStream長度,InputStream指標在首部,可在當前指標位置,通過mark標記位置,引數為標記位無效前的已讀位元組長,已讀的位元組數超過此引數,標記位無效,reset也不能將指標返回此標記位,注意:已讀位元組長相對於mark標記位置開始,而非從InputStream的頭部開始 */
    inputStream.mark(count);
  
    inputStream.reset();
  
    /** 指標移動至當前指標1024個位元組後 */
    inputStream.read(new byte[1024]);

    /** 更新:從網路中獲取inputstream,並得到其長度時,如果網路阻塞,inputstream的available()會小於完整長度,甚至為0,推薦: */
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
         e.printStackTrace();
    }

    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpURLConnection.getContentLength();