Reading a text file with Java
Saturday, February 20th, 2010Recently I regularly use Java in some classes and my research. In particular, I often implement a similar code to read a text file for the purpose of some text processing. So I will attach the trivial code to this post for future reference. I confirmed that it works with Java 1.6.0_16.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
class SomeClass {
public static void readFromFile(String filename) {
BufferedReader fin = null;
try {
fin = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = fin.readLine()) != null) {
// Do something
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fin != null) fin.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
readFromFile("sample.txt");
}
}
Incidentally I have used BufferedReader rather than BufferedInputStream simply because BufferedReader is more suitable to the text processing that I need to do right now.