Question

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 :)

Was it helpful?

Solution

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.

OTHER TIPS

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top