Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Basic File Reading

  Asked By: Michael    Date: Aug 29    Category: Java    Views: 789

I am working on a program that read in a text file. Below is the
code that I am currently using
public void load_file()
FileReader fp;
char[] reading_buffer = new char[1024];

fp = new FileReader(new File(file_name));
while (fp.read(reading_buffer) != -1)
buffer += new String(reading_buffer);
catch(IOException event)
file_name (protected String file_name) and buffer (protected String
buffer) are class member.
For the most part this works, but if the file is not a 1024*x bytes
in size, the end of buffer will contain unknown character (stuff not
in the file) to make the length of reading_buffer 1024*x bytes.

Why do I get this garbage character?

I am mostly a C/C++ programmer, so I am sure there is a more
efficient way to accomplish this, but I don't know what it is, this
just seemed the most normal (comeing from a C/C++ point of view).
Can anyone tell me a better way to accomplish this?



4 Answers Found

Answer #1    Answered By: Hubert Taylor     Answered On: Aug 29

The read  method returns how many characters it read before it reached the end  of
file. So, I don't see how the garbage character  should be a problem. In fact,
your garbage  character may just be an end of file  character.

Answer #2    Answered By: Lurlene Fischer     Answered On: Aug 29

here is a perfect collection of code snippets:
You will find a solution to your problem there as well.
This URL is always a good stop when having these "simple" problems.

Answer #3    Answered By: Helene Stewart     Answered 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);
} catch (FileNotFoundException fnfe) {
System.err.println("File '" + infile + "' not found.");
} catch (IOException ioe) {
System.err.println("Error reading  '" + infile + "'.");

Answer #4    Answered By: Feodora Bonkob     Answered On: Aug 29

That fixed my problem, and I actually do notice a
significant preformance improvement (I am working  with fairly large

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