java如何读取数据输入流两次或两次以上?
我有一个到我在别处托管的应用程序的socket连接。一旦我连接了,我做了一个OutputStream
和DataInputStream
连接完成后,我使用OutputStream
向应用程序发送握手包。一旦这个握手被批准,它就会通过DataInputStream
(1)返回一个数据包
这个数据包被处理并返回给应用程序,带有OutputStream
如果返回的数据有效,我从DataInputStream
(2)中获得另一个数据包。然而,我无法通过DataInputStream
阅读此数据包
我试图使用DataInputStream.markSupported()
和DataInputStream.mark()
,但这没有给我任何帮助(除了一条空的异常消息)
是否可以再次读取输入流?如果是这样,有人能指出我做错了什么吗
编辑:以下是我的解决方案:
// First define the Output and Input streams.
OutputStream output = socket.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
// Send the first packet to the application.
output.write("test"); // (not actual data that I sent)
// Make an empty byte array and fill it with the first response from the application.
byte[] incoming = new byte[200];
bis.read(incoming); //First packet receive
//Send a second packet to the application.
output.write("test2"); // (not actual data that I sent)
// Mark the Input stream to the length of the first response and reset the stream.
bis.mark(incoming.length);
bis.reset();
// Create a second empty byte array and fill it with the second response from the application.
byte[] incoming2 = new byte[200];
bis.read(incoming2);
我不确定这是否是最正确的方法,但这种方法对我很有效
# 1 楼答案
我会使用ByteArrayInput流或者一些你可以重置的东西。这将涉及将数据读入另一种类型的输入流,然后创建一个输入流
InputStream有一个
markSupported()
方法,您可以检查原始数组和字节数组,以找到标记将使用的方法:https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#markSupported() https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html