我正在尝试使用 BufferedInputStream 中的 BufferedReader 从套接字流中读取第一行,它读取第一行(1),这是此内容中某些内容(2)的大小,我有另一个内容的大小(3)
- 正确读取...
(使用 BufferedReader, _bin.readLine() )
- 读取也正确...
( with _in.read(byte[] b) )
- 不会读,似乎 (2) 中的内容比我读的内容多
我认为问题是我正在尝试使用 BufferedReader
进行读取,然后使用 BufferedInputStream。
..任何人都可以帮助我吗?
public HashMap<String, byte[]> readHead() throws IOException {
JSONObject json;
try {
HashMap<String, byte[]> map = new HashMap<>();
System.out.println("reading header");
int headersize = Integer.parseInt(_bin.readLine());
byte[] parsable = new byte[headersize];
_in.read(parsable);
json = new JSONObject(new String(parsable));
map.put("id", lTob(json.getLong(SagConstants.KEY_ID)));
map.put("length", iTob(json.getInt(SagConstants.KEY_SIZE)));
map.put("type", new byte[]{(byte)json.getInt(SagConstants.KEY_TYPE)});
return map;
} catch(SocketException | JSONException e) {
_exception = e.getMessage();
_error_code = SagConstants.ERROR_OCCOURED_EXCEPTION;
return null;
}
}
抱歉英语不好,解释不好,我试图解释我的问题,希望你理解
文件格式如下:
size1
{json, length is given size1, there is size2 given}
{second json, length is size2}
_in 是 BufferedInputStream();
_bin 是 BufferedReader(_in);
使用 _bin,我读取第一行(size1)并转换为整数
使用 _in,我读取下一个数据,其中 size2 是 size2,该数据的长度是 size1
然后我尝试读取最后一个数据,它的大小是size2
像这样的东西:
byte[] b = new byte[secondSize];
_in.read(b);
这里没有任何反应,程序已暂停...
最佳答案
can't work with BufferedInputStream and BufferedReader together
这是正确的。如果您在套接字上使用任何缓冲流或读取器[或实际上任何数据源],则您不能使用任何其他流或读取器。数据将在缓冲流或读取器的缓冲区中“丢失”,也就是说预读,并且无法供其他流/读取器使用。
您需要重新考虑您的设计。
关于java - 不能与 BufferedInputStream 和 BufferedReader 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28585177/