1

I don't understand why the first variant is working and the second is not.

BufferedReader reader = new BufferedReader(new InputStreamReader(in, charsetName));
try {            
    char[] buffer = new char[4096];
    reader.read(buffer, 0, 4096);
    return new String(buffer);
} finally {
    reader.close();
}

BufferedReader reader = new BufferedReader(new InputStreamReader(in, charsetName));
try {
    int size = 0;
    int ch=0;
    while ((ch=reader.read())!=-1){
        size++;
    }
    char[] buffer = new char[size];
    reader.read(buffer, 0, size);
    return new String(buffer);
} finally {
    reader.close();
}
M A
  • 71,713
  • 13
  • 134
  • 174
user3505689
  • 97
  • 1
  • 1
  • 10
  • 1
    In your non-working version, the file pointer is located at the end of the file after the `read` loop. You need to rewind the file to its starting position. – Jongware Jul 03 '14 at 09:38

2 Answers2

3

Firstly, both of your snippets are broken. Your're calling read without taking any notice of the return value. There could be more data to be read, and it may very well not have filled the buffer... but you're using the whole buffer anyway.

Next, your second piece of code is reading to the end of the content... and then trying to read more content. That's not going to work.

I'd strongly suggest abandoning doing this yourself, and using something like Files.toString(File, Charset) from Guava. There's no need to reinvent the wheel here, and if you did want to reinvent it, you'd need to change quite a lot of your code. (I'd probably start from scratch...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

BufferedReader use a sort of pointer in the file to locate the position from where he should read , this pointer change whenever we call read(*) method. so in your case the second want will read nothing because the pointer has reach the end of the file.

Mifmif
  • 3,132
  • 18
  • 23
  • i got it, but how to get to know the size of the stream without using the first read? – user3505689 Jul 03 '14 at 09:46
  • 1
    if you build your input stream from a file then you can get the site by calling `file.length()` . if not then try to convert InputStream to ByteArrayInputStream check [this](http://stackoverflow.com/a/17861016/1250229) – Mifmif Jul 03 '14 at 09:59