neutralh neutralh - 1 month ago 19
Java Question

Java InputStream blocking only if used InputStreamReader

I am trying to access the underlying InputStream of the InputStreamReader but it only blocks even though there is data, when I use InputStream with out InputStreamReader it reads, when I add InputStreamReader to InputStream, I can no longer use the underlying InputStream or it will block.

InputStream in = socket.getInputStream();
OutputStream theOutput = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in,StandardCharsets.US_ASCII));

String line = br.readLine();
System.out.println(line);
if(line.equals(Operation_Map_Upload)){
String MapName = br.readLine();
System.out.println(MapName);

String MapMaker = br.readLine();
System.out.println(MapMaker);
String MapData = br.readLine();
System.out.println(MapData);

int ThumbnailSize = Integer.parseInt(br.readLine());
System.out.println(ThumbnailSize);
byte[] Thumbnail = new byte[ThumbnailSize];
in.read(Thumbnail, 0, ThumbnailSize); // <---block here
int MapID = SaveMap(MapName, MapMaker, MapData, Thumbnail);

theOutput.write(("Success;"+MapID).getBytes(StandardCharsets.US_ASCII));
theOutput.flush();

}


If I read one more line using InputStreamReader it reads ok, but if instead I try to read 1 byte using InputStream it will block.

EJP EJP
Answer

That is correct. InputStreamReader is buffered so it reads ahead, so the next byte you read directly from the InputStream won't be the one you want anyway. You can't do this.

Comments