Try using the code below. I cut it out of a program I wrote. What
you are failing to catch in your code is the number of characters
returned by the read() method. Also notice that I am only putting the
number of characters returned by read() into the StringBuffer. This
ensures that no extra characters are put into the resulting string.
Also because I am using a StringBuffer instead of string this code
should execute a bit faster than yours.
final int BUFSIZE = 1024;
String infile = "xxxxxxx";
StringBuffer inbuf = new StringBuffer();
try {
FileReader fr = new FileReader(infile);
char c[] = new char[BUFSIZE];
int cnt = 0;
while ((cnt = fr.read(c, 0, BUFSIZE)) >= 0) {
if (cnt > 0) {
inbuf.append(c, 0, cnt);
}
}
fr.close();
} catch (FileNotFoundException fnfe) {
System.err.println("File '" + infile + "' not found.");
} catch (IOException ioe) {
System.err.println("Error reading '" + infile + "'.");
}