Posted By

trusktr on 10/16/10


Tagged

java io files textfiles inputoutput


Versions (?)

How to read from a file in Java


 / Published in: Java
 

Use this to read from a file. It is wrapped in a try/catch statement in case something breaks when trying to read the file. It will simply throw and exception (error) and continue rather than crashing your app.

  1. import java.io.*
  2.  
  3. /**
  4.  * This program reads a text file line by line and prints them to the console. It uses
  5.  * FileReader and BufferedReader to read the file.
  6.  *
  7.  */
  8. public class FileInput {
  9.  
  10. public static void main(String[] args) {
  11. File file = new File("MyFile.txt");
  12. FileReader fr = null;
  13. BufferedReader br = null;
  14. try {
  15. fr = new FileReader(file);
  16. br = new BufferedReader(fr);
  17. while (br.ready()) { // br.read() returns false when the Buffer is not ready (end of file).
  18. System.out.println(br.readLine()); // this statement reads a line from the file and prints it to the console (and moves to next line and is "ready" if there IS a next line).
  19. }
  20. br.close(); // dispose of the resources after using them.
  21. }
  22. catch (FileNotFoundException e) { // File not found.
  23. e.printStackTrace();
  24. // Put something here like an error message.
  25. System.out.println("The file could not be found.");
  26. }
  27. catch (IOException e) { // Error with transaction.
  28. e.printStackTrace();
  29. // Put something here like an error message.
  30. System.out.println("There was an error reading the file.");
  31. }
  32. }
  33. }

Report this snippet  

You need to login to post a comment.