read line java line by line code example

Example 1: 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();
          }

Example 2: java read next line

Scanner scanner = new Scanner(new File("filename"));
while (scanner.hasNextLine()) {
   String line = scanner.nextLine();
   // process the line
}

Tags:

Java Example