2017-06-08 112 views
0

我試圖通過調用getBytes()方法來獲取InputStream中的字節數組數據,但沒有任何內容正在打印在控制檯中。 vlaue的計數9.如何打印出InputStream的字節?從InputStream獲取字節數組

import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.ServerSocket; 
import java.net.Socket; 


public class Test { 

    public static void main(String args[]) throws Exception { 
     InputStream inputStream = null; 
     ServerSocket serverSocket = new ServerSocket(27015); 
     while (true) { 
      Socket clientSocket = serverSocket.accept(); 
      inputStream = clientSocket.getInputStream(); 
      byte[] temp = new byte[512]; 
      int count = inputStream.read(temp); // here I am getting 9 
      byte[] byteData = Test.getBytes(inputStream); // byteData is here empty. 
      System.out.println("byteData: " + byteData); 

     } 
    } 


    public static byte[] getBytes(InputStream is) throws IOException { 

     int len; 
     int size = 512; 
     byte[] buf; 

     if (is instanceof ByteArrayInputStream) { 
      size = is.available(); 
      buf = new byte[size]; 
      len = is.read(buf, 0, size); 
     } else { 
      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
      buf = new byte[size]; 
      while ((len = is.read(buf, 0, size)) != -1) { 
       bos.write(buf, 0, len); 
      } 
      buf = bos.toByteArray(); 
     } 
     return buf; 
    } 

} 

回答

2

在該行:

int count = inputStream.read(temp); // here I am getting 9 

您已經閱讀文件alredy才結束,

太行:

 byte[] byteData = Test.getBytes(inputStream); // byteData is here empty. 

沒有什麼閱讀。

所以你應該刪除第一行,並將數組的長度作爲輸入流中的字節數