I know I should know how to read a file with Java, but old dogs die hard, or something. At any rate, I found a great example that even works. I got the code from here:
Read from a file using a BufferedReader – A Java Code Example.
And here’s what I came up [...]
I know I should know how to read a file with Java, but old dogs die hard, or something. At any rate, I found a great example that even works. I got the code from here:
Read from a file using a BufferedReader – A Java Code Example.
And here’s what I came up with:
public static String readFileToString(String fileName) {
BufferedReader bufferedReader = null;
StringBuffer output = new StringBuffer();
try {
bufferedReader = new BufferedReader(new FileReader(fileName));
String line = null;
String delim = "";
while ((line = bufferedReader.readLine()) != null) {
output.append(delim);
output.append(line);
delim = "\n";
}
} catch (FileNotFoundException ex) {
log.error(ex);
} catch (IOException ex) {
log.error(ex);
} finally {
//Close the BufferedReader
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
log.error(ex);
}
}
return output.toString();
}
Update: After thinking about this a little more I decided to use the Apache Commons FileUtils class to do the work for me. It simplifies things a little.
public static String readFileToString(File pInputFile) {
try {
return FileUtils.readFileToString(pInputFile, "ISO-8859-1");
} catch (IOException e) {
log.error(e);
}
}
My question to my readers is, how is the best way to write test case for file reading? Any takers?
(image by As Good)
You have arrived at my personal blog site. There’s not much here yet, but I plan on using this site to write my rambling thoughts on life, work, play and relationship.
You have arrived at my personal blog site. There’s not much here yet, but I plan on using this site to write my rambling thoughts on life, work, play and relationship.
-
Calendar
February 2012 S M T W T F S « Nov 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 -
Meta
