如何将整个输入流读到字节数组?
当前回答
Input Stream is ...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
bos.write(next);
next = in.read();
}
bos.flush();
byte[] result = bos.toByteArray();
bos.close();
其他回答
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
int r = in.read(buffer);
if (r == -1) break;
out.write(buffer, 0, r);
}
byte[] ret = out.toByteArray();
这是我的复制粘贴版本:
@SuppressWarnings("empty-statement")
public static byte[] inputStreamToByte(InputStream is) throws IOException {
if (is == null) {
return null;
}
// Define a size if you have an idea of it.
ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
byte[] read = new byte[512]; // Your buffer size.
for (int i; -1 != (i = is.read(read)); r.write(read, 0, i));
is.close();
return r.toByteArray();
}
你可以使用Cactoos(我是它的开发者之一):
import org.cactoos.bytes.BytesOf;
byte[] array = new BytesOf(stream).asBytes();
你也可以将流转换为字符串:
import org.cactoos.text.TextOf;
String txt = new TextOf(stream).asString();
asBytes()和asString()方法都会抛出checked Exception。如果你不想捕获它,使用Unchecked*装饰器,例如:
import org.cactoos.bytes.BytesOf;
import org.cactoos.bytes.UncheckedBytes;
byte[] array = new UncheckedBytes(new BytesOf(stream)).asBytes();
另一种情况是在发送请求到服务器并等待响应后,通过流获得正确的字节数组。
/**
* Begin setup TCP connection to PC app
* to open integrate connection between mobile app and pc app (or mobile app)
*/
mSocket = new Socket(IP, port);
// mSocket.setSoTimeout(30000);
DataOutputStream mDos = new DataOutputStream(mSocket.getOutputStream());
String str = "MobileRequest#" + params[0] + "#<EOF>";
mDos.write(str.getBytes());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/* Since data are accepted as byte, all of them will be collected in the
following byte array which initialised with accepted data length. */
DataInputStream mDis = new DataInputStream(mSocket.getInputStream());
byte[] data = new byte[mDis.available()];
// Collecting data into byte array
for (int i = 0; i < data.length; i++)
data[i] = mDis.readByte();
// Converting collected data in byte array into String.
String RESPONSE = new String(data);
和往常一样,Spring框架(Spring core从3.2.2开始)也为你提供了一些东西:
推荐文章
- 我如何修复一个NoSuchMethodError?
- Maven surefire找不到ForkedBooter类
- Java 8:我如何在流中使用异常抛出方法?
- 去下一次迭代在java For循环
- 在Java中使用什么数据类型来表示钱?
- Class.getResource()和ClassLoader.getResource()之间的区别是什么?
- 如何通过传递特定日期来确定星期几?
- 如何将DecimalFormat的小数分隔符从逗号更改为点/点?
- 控制jar工件的Maven最终名称
- Spring-MVC控制器中的404触发器?
- 为什么生成较长的serialVersionUID而不是简单的1L?
- JAX-RS / Jersey如何自定义错误处理?
- 从标准输入中捕获字符,而不需要等待按enter键
- 在执行JpaTest时无法找到@SpringBootConfiguration
- _JAVA_OPTIONS, JAVA_TOOL_OPTIONS和JAVA_OPTS之间的区别