Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Michael Cox   on Aug 29 In Java Category.

  
Question Answered By: Helene Stewart   on Aug 29

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 + "'.");
}

Share: 

 

This Question has 3 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Basic File Reading Or get search suggestion and latest updates.


Tagged: