Ivan
Ivan

Reputation: 503

Java: problem with reading a file

I'm loading an XML file with this method:

public static String readTextFile(String fullPathFilename) throws IOException {
        StringBuffer sb = new StringBuffer(1024);
        BufferedReader reader = new BufferedReader(new FileReader(fullPathFilename));

        char[] chars = new char[1024];
        while(reader.read(chars) > -1){
            sb.append(String.valueOf(chars));   
        }

        reader.close();

        return sb.toString();
    }

But it doesn't load the whole data. Instead of 25634 characters, it loads 10 less (25624). Why is that?

Thanks,

Ivan

Upvotes: 1

Views: 246

Answers (4)

Bernd Elkemann
Bernd Elkemann

Reputation: 23560

Use FileInputStream to avoid certain characters getting recognized as utf-8:

StringBuffer sb = new StringBuffer(1024);
FileInputStream fis = new FileInputStream(filename);
char[] chars = new char[1024];
while(reader.read(chars) > -1){
    sb.append(String.valueOf(chars));   
}
fis.close();

return sb.toString();

Upvotes: 0

Philipp Wendler
Philipp Wendler

Reputation: 11423

Perhaps you have 25634 Bytes in your file that represent only 25624 Characters? This might happen with multibyte character sets like UTF-8. All InputStreamReader (including FileReader) automatically do this conversion using a Charset (either an explicitly given one, or the default encoding that depends on the platform).

Upvotes: 0

oliholz
oliholz

Reputation: 7507

With BufferedReader you get the readLine()-Method, which works well for me.

        StringBuffer sb = new StringBuffer( 1024 );
        BufferedReader reader = new BufferedReader( new FileReader( fullPathFilename ) );

        while( true ) {
            String line = reader.readLine();
            if(line == null) {
                break;
            }
            sb.append( line );
        }
        reader.close();

Upvotes: 1

Joel
Joel

Reputation: 30166

I think there's a bug in your code, the last read might not necessarily fill the char[], but you still load the string with all of it. To account for this you need to do something like:

    StringBuilder res = new StringBuilder();
    InputStreamReader r = new InputStreamReader(new BufferedInputStream(is));
    char[] c = new char[1024];
    while(true) {
        int charCount = r.read(c);
        if (charCount == -1) {
            break; 
        }
        res.append(c, 0, charCount);
    }
    r.close();

Also, how do you know you're expecting 25634 chars?

(and use StringBuilder instead of StringBuffer, the former is not threadsafe so sightly faster)

Upvotes: 1

Related Questions