Read lines of text from a file with the BufferedReader class




This example shows how to read the contents of a file line by line.
By using the BufferedReader class we can read line-by-line without having to worry about
linebreaks. We just call it's readLine() method.




package je_test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileUtil {

  public void readLinesFromFile(String filename) {

    BufferedReader br = null;

    try {

      br = new BufferedReader(new FileReader(filename));

      String line = null;
      while ((line = br.readLine()) != null) {

        //Process the line just read.
        //Here we just echo it to standard output.
        System.out.println(line);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {

      //Close the BufferedReader
      if (br != null) {
        try {
          br.close();
        }
        catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

  }

  public static void main(String[] args) {
    FileUtil util = new FileUtil();
    util.readLinesFromFile("myfile.txt");
  }
}

 
Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark: Social bookmarks del.icio.us digg Furl YahooMyWeb blinkbits BlinkList blogmarks co.mments connoteas De.lirio.us Fark feedmelinks LinkaGoGo Ma.gnolia NewsVine Netvouz RawSugar Reddit scuttle Shadows Simpy Smarking Spurl TailRank Wists segnalo




   Need Java help? You are just a few bucks away.

   This is how it works:
  • Send us a detailed description of what you need help with.
  • We send you a confirmation when we start working on your request, and then we send you the compiled Java code for you to test out.
  • If you are satisfied with the result we send you a secure link where you can make the payment for the Java source code, usually a few bucks (depends on the work required).
  • The source code is sent to you once the payment is completed.


Write your detailed request here:
   

E-mail address: