[英]Difference between BufferedReader and BufferedInputStream
[英]can't work with BufferedInputStream and BufferedReader together
我正在尝试使用BufferedInputStream的BufferedReader从套接字流中读取第一行,它读取第一行(1),这是该内容中某些内容的大小(2),而我具有另一内容(3)的大小
( with BufferedReader, _bin.readLine() )
( with _in.read(byte[] b) )
我认为问题是我正在尝试使用BufferedReader
和BufferedInputStream.
进行读取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,我读取第一行(大小1)并转换为整数
与_in,我读取下一个数据,其中size2是,此数据的长度是size1
然后即时通讯试图读取最后一个数据,其大小为size2
像这样的东西:
byte[] b = new byte[secondSize];
_in.read(b);
而且这里什么也没有发生,程序已暂停...
不能与BufferedInputStream和BufferedReader一起使用
没错 如果在套接字[或实际上是任何数据源]上使用任何缓冲的流或读取器,则不能将其与任何其他流或读取器一起使用。 数据将在缓冲的流或读取器的缓冲区中“丢失”,即提前读取,而其他流/读取器将无法使用。
您需要重新考虑您的设计。
您创建了一个BufferedReader
_bin和BufferedInputStream
_in并读取了两个文件,但是它们的光标位置不同,因此第二次读取从头开始,因为您使用2对象读取它。 您也应该使用_in读取size1。
int headersize = Integer.parseInt(readLine(_in));
byte[] parsable = new byte[headersize];
_in.read(parsable);
在readLine下面使用BufferedInputStream
读取所有数据。
private final static byte NL = 10;// new line
private final static byte EOF = -1;// end of file
private final static byte EOL = 0;// end of line
private static String readLine(BufferedInputStream reader,
String accumulator) throws IOException {
byte[] container = new byte[1];
reader.read(container);
byte byteRead = container[0];
if (byteRead == NL || byteRead == EOL || byteRead == EOF) {
return accumulator;
}
String input = "";
input = new String(container, 0, 1);
accumulator = accumulator + input;
return readLine(reader, accumulator);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.