gpt4 book ai didi

java - 从InputStream中获取字节数组

转载 作者:行者123 更新时间:2023-12-02 02:46:54 25 4
gpt4 key购买 nike

我试图通过调用 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;
}

}

最佳答案

行中:

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

您已阅读完该文件,

所以这行:

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

没有什么可读的。

因此您应该删除第一行并将数组的长度作为输入流中的字节数

关于java - 从InputStream中获取字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com