java read file as lines code example

Example 1: java read each lines in file

BufferedReader br = null;
        try {
            File file = new File("myfile.txt"); // java.io.File
            FileReader fr = new FileReader(file); // java.io.FileReader
            br = new BufferedReader(fr); // java.io.BufferedReader
            String line;
            while ((line = br.readLine()) != null) {
              // process the line
            }
          }
          catch(IOException e) { e.printStackTrace();}
          finally
          {
              try { if (br != null) br.close(); }
              catch(IOException e) { e.printStackTrace(); }
          }

Example 2: java read lines from file

Scanner sc = null;
        try {
            File file = new File("myfile.txt"); // java.io.File
            sc = new Scanner(file);     // java.util.Scanner
            String line;
            while (sc.hasNextLine()) {
              line = sc.nextLine();
              // process the line
            }
          }
          catch(FileNotFoundException e)
          {
              e.printStackTrace();
          }
          finally {
            if (sc != null) sc.close();
          }

Tags:

Java Example