java - 如何正确读取具有多个内容的 InputStream
问题描述
public static void main(String[] args) throws Exception
{
// Server sends 3 numbers to the client
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(1000);
bos.write(2000);
bos.write(3000);
// Client receive the bytes
final byte[] bytes = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
System.out.println(bis.read());
System.out.println(bis.read());
System.out.println(bis.read());
}
上面的代码是中断的,因为bis.read()
返回了一个 0 到 255 范围内的 int
我怎样才能正确接收这些号码?我应该使用分隔符并继续阅读流直到找到它吗?如果是这样,如果我要发送多个文件怎么办,我认为如果分隔符作为单个字节它可以匹配文件中的某个位置并且也会中断。
解决方案
为您的流使用装饰器!
你所要做的就是用java.io.ObjectOutputStream
/ 和包装你的输出和输入流java.io.ObjectInputStream
。writeInt
这些类支持通过对/的单个方法调用来写入和读取整数(一个 4 字节值)readInt
。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeInt(1000);
os.writeInt(2000);
os.writeInt(3000);
os.close();
// Client receive the bytes
final byte[] bytes = bos.toByteArray();
ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(bytes));
System.out.println(is.readInt());
System.out.println(is.readInt());
System.out.println(is.readInt());
不要忘记关闭流。使用 try/finally 或 try-with-resources。
推荐阅读
- java - Firestore DocumentReference 数据类型无法使用 Gson 库进行序列化/反序列化
- php - 注意:未定义索引:/home/webccans/public_html/index.php 中的 REDIRECT_URL
- clang - 有没有办法禁用特定的 llvm lld 警告?
- python - Python lxml 和 xslt 问题
- python - numba 给出 NumPy 的错误
- ssl - 如何在 Iris GoLang 框架中为通配符子域设置 AutoTLS
- ios - 与一个通知交互后清除所有通知
- c++ - 0x0F50DF58 处未处理的异常:0xC0000005:访问冲突读取位置 0x0047CA04
- wordpress - 机器人访问网站时可以运行 WordPress cron 作业吗?
- mysql - SQL 子查询按列值获取行