从InputStream获取字节数组

时间:2017-06-08 12:29:58

标签: java

我试图通过调用getBytes()方法获取InputStream中的字节数组数据,但控制台中没有打印任何内容。计数值为vlaue 9.如何打印出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;
    }

}

1 个答案:

答案 0 :(得分:2)

在该行:

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

你已经阅读了文件alredy直到最后,

所以行:

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

无需阅读。

所以你应该删除第一行并将数组的长度作为输入流中的字节数