Problems with getting number of chars in a file

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();
}
Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow