views:

252

answers:

2

I'm having an issue reading from a java input stream. I have a buffer of size 1024, and an input stream of size 29k-31k. I read the inputStream in a loop, but I only get 29 bytes for the first read, 39 for the second read, and nothing after that. The same behavior repeats for different InputStreams. (I'm writing the data to an output stream but I don't see how this can affect the first read)

  int bytesRead = 0;
  byte[] byteBuf = new byte[1024];

  OutputStream fileStream = FileUtil.openFileForWrite(saveTo);

  bytesRead = reader.read(byteBuf);
  while(bytesRead!=-1){
   fileStream.write(byteBuf, 0, bytesRead);
   bytesRead = reader.read(byteBuf);
  }

What am I missing?

Any help is appreciated :)

+1  A: 

Where are you getting the input stream from? How do you know that it's 29K-31K?

Your code looks reasonable to me, although I generally structure the loop slightly different to avoid the duplication of the read call.

Jon Skeet
I knew the inputStream is coming from an HTTPConnection, what I missed is that my colleague added a line to test a custom InputStream class that was causing the error. Should have gone back earlier, thanks for the tip! :)
Tamar
A: 

Have you tried using readline() instead of read()?

Path file = ...;
InputStream in = null;
try {
    in = file.newInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException x) {
    System.err.println(x);
} finally {
    if (in != null) in.close();
}
Jeff Leonard
That's assuming that it's text data to start with, and doesn't give any idea for why it might be happening in the first place.
Jon Skeet