1

I'm trying to read UTF-16 string from a Socket. And the point is I don't know its length in bytes before I read first few chars of the string.

So I've opened InputStreamReader like this:

InputStreamReader reader = new InputStreamReader(inputStream, "UTF-16");

And then I tried to read it char by char.

reader.read();

And it hangs while trying to read the very first char!

In a process of debugging I realized that it looks like InputStreamReader kinda tries to read WHOLE InputStream, and then converts it to UTF-16 char sequence. And of course, it goes all the way down to end of string, and it's nothing there, so it just waits for the client to send some more bytes.

Is that really the way InputStreamReader works? If it is - how can I read a PART of UTF-16 InputStream, or better one single char, without reaching end of it?

user1748526
  • 464
  • 5
  • 18

2 Answers2

-1

if i understand you pb you should translate your inputstream into a string using a byte[] with

IOUtils.toString(inputStream, StandardCharsets.UTF_8);

then you should be able to iterate on it

or directly

FileUtils.readFileToByteArray(new File(path))

if you want to get a byte[] from the file

Aurele Collinet
  • 138
  • 1
  • 16
-1

As the BufferedInputStream method you are using does not block you get the situation that as soon as your InputStream does not have any data and is not closed you don't get a -1 but a 0. This will send your method into an endless loop.

So for reading local streams it is better to check for read() <= 0 as you usually get the data fast enough. The best way is to make sure there is an eof by closing the stream.

MBaev
  • 353
  • 2
  • 20