attaboy182
attaboy182

Reputation: 2079

Reading from InputStream and appending to String

I tried two difference approaches to read bytes from the InputStream and append the contents to a string/print the string:

1.)

buffer= new byte[32768];
   while((read= is.read(buffer))>0){
          System.out.println(new String(buffer));
    }

2.)

     BufferedReader br = null;
     StringBuilder sb = new StringBuilder();
     String line;
     br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
               sb.append(line);
        }
      br.close();

While the second approach works, the first approach gets only the first few bytes and stops.

Could someone please tell me what's wrong with approach 1?

Upvotes: 0

Views: 1286

Answers (4)

Yong
Yong

Reputation: 21

new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136112

Approach 1 is wrong because it does not take into account ther real number of bytes which is.read(buffer) reads into buffer

Approach 2 is wrong because it discards end of line characters.

Consider java.nio.file.Files.readAllBytes or readAllLines

Upvotes: 2

VGR
VGR

Reputation: 44414

The first approach fails because you are ignoring the value returned by is.read(buffer). There is no guarantee that the InputStream.read will fill your byte array. That's why the method returns the number of bytes it actually read.

The contract for the InputStream.read method describes this in detail.

The second approach will strip newlines. I'm not sure if that's what you want.

Be aware that both approaches assume the InputStream's bytes represent characters using your computer's default charset. If the characters were sent from a source which encoded them with a different charset, expect the characters to be corrupted in your String.

Upvotes: 1

Rahul
Rahul

Reputation: 3519

In First approach you have defined byte size as 32768. Now let us consider that you file size is 97536 bytes. When you are reading bytes using (read= is.read(buffer)) at first time it will read 32768 bytes and in second time it will read again 32768 bytes but for third time it will read only 32000 bytes since (32768+32768+32000=97536) equal to file size. Now buffer at index 32000 onwards contains earlier data and you are printing whole buffer. Thus this data is extra bytes which were filled in just before the last looping.

Thus Your first approach is not reading incomplete bytes, instead it is printing extra bytes.

Upvotes: 0

Related Questions