Can't read a text file using java
Hi All
I am trying to read a log file.
ProgramA keeps updating the log file, while my program ProgramB reads it.
For some readson my ProgramB is not able to read the last two lines in the log file. If I run the program in debug mode it is reading all the lines.
This is having me frustrated.
Please let me know if there is a way to read entire contents.
Here is how I am reading the files ( 2ways)
/*
private static String readFileAsString(String filePath)
throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
FileReader fr = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fr);
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
fr.close();
return fileData.toString();
}
*/
/**
* Fetch the entire contents of a text file, and return it in a String.
* This style of implementation does not throw Exceptions to the caller.
*
* @param aFile is a file which already exists and can be read.
*/
staticpublic String readFileAsString(String filePath){
//...checks on aFile are elided
StringBuffer contents =new StringBuffer();
//declared here only to make visible to finally clause
BufferedReader input =null;
try{
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
input =new BufferedReader(new FileReader(filePath) );
String line =null;//not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) !=null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex){
ex.printStackTrace();
}
catch (IOException ex){
ex.printStackTrace();
}
finally{
try{
if (input!=null){
//flush and close both "input" and its underlying FileReader
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
return contents.toString();
}

