Skip to content

Instantly share code, notes, and snippets.

@marcoshack
Created February 5, 2009 20:08
Show Gist options
  • Save marcoshack/58967 to your computer and use it in GitHub Desktop.
Save marcoshack/58967 to your computer and use it in GitHub Desktop.
File reading in Java
/**
* Read a file line by line in Java using FileReader and BufferedReader.
* @author Marcos Hack <marcoshack@gmail.com>
*/
public class FileReader {
String fileName = "/path/to/your/file";
try {
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
String currentLine;
do {
line = bufferedReader.readLine();
if (line != null) {
// DO WHAREVER YOU WANT WITH THE LINE
}
} while (line != null);
} catch (FileNotFoundException notFoundEx) {
System.err.println("File not found: \"" + fileName);
} catch (IOException ioEx) {
log.error("Error reading file \"" + fileName + "\"", ioEx);
} finally {
try {
if (fileReader != null) {
fileReader.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ioEx) {
log.error("Fail to close file \"" + fileName + "\"", ioEx);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment