2014-04-28 68 views
2

我目前正在嘗試從服務器響應讀取數據。我使用Socket連接到服務器,創建一個http GET請求,然後使用Buffered Reader讀取數據。下面是代碼的樣子壓實:如何從Java中的InputStream讀取並轉換爲字節數組?

Socket conn = new Socket(server, 80); 
    //Request made here 
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
    String response; 
    while((response = inFromServer.readLine()) != null){ 
     System.out.println(response); 
    } 

我想在讀取數據,而不是作爲一個字符串,作爲一個字節數組,並將其寫入文件。這怎麼可能?任何幫助非常感謝,謝謝。

+0

可能重複[BufferedReader中直接以字節爲\ [\](http://stackoverflow.com/questions/15107104/bufferedreader-directly-to-byte) –

回答

2

你需要使用一個ByteArrayOutputStream,做像下面的代碼:的

Socket conn = new Socket(server, 80); 
     //Request made here 
     InputStream is = conn.getInputStream(); 

     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     byte[] buffer = new byte[1024]; 
     int readBytes = -1; 

     while((readBytes = is.read(buffer)) > 1){ 
      baos.write(buffer,0,readBytes); 
     } 

     byte[] responseArray = baos.toByteArray(); 
+0

非常感謝你許多。這非常有幫助。然而,我只有一個問題。因此,HTTP響應格式化的方式首先是標題,然後是文件內容。所以爲了創建一個合適大小的字節數組,我必須首先解析頭並獲取信息,然後讀取文件。你會如何推薦這樣做? – user3579421

+0

鑑於你的問題不適合推薦一個稍微不同的方法,首先閱讀作爲文本(2部分)標題和內容的響應。使用'getBytes()' – AdityaKeyal

+0

將文本內容轉換爲字節數組我認爲這是。將它作爲文本而不是字節讀取的時間會有差異嗎?因爲我這裏的全部目的是計算下載速度,而且我看過的代碼已經以字節的形式下載了文件。 – user3579421

1

一種方法是使用Apache的commons-io的IOUtils

byte[] bytes = IOUtils.toByteArray(inputstream); 
0

用普通的Java:

ByteArrayOutputStream output = new ByteArrayOutputStream(); 

    try(InputStream stream = new FileInputStream("myFile")) { 
     byte[] buffer = new byte[2048]; 
     int numRead; 
     while((numRead = stream.read(buffer)) != -1) { 
      output.write(buffer, 0, numRead); 
     } 
    } catch(IOException e) { 
     e.printStackTrace(); 
    } 

    // and here your bytes 
    byte[] myDesiredBytes = output.toByteArray(); 
0

如果你不使用Apache的commons-IO庫在你的項目中,我有很簡單方法做同樣不使用它..

/* 
    * Read bytes from inputStream and writes to OutputStream, 
    * later converts OutputStream to byte array in Java. 
    */ 
    public static byte[] toByteArrayUsingJava(InputStream is) 
    throws IOException{ 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     int reads = is.read(); 

     while(reads != -1){ 
      baos.write(reads); 
      reads = is.read(); 
     } 

     return baos.toByteArray(); 

    } 
相關問題