Created
February 5, 2009 20:08
-
-
Save marcoshack/58967 to your computer and use it in GitHub Desktop.
File reading in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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