read line method in java code example
Example 1: find in line java
import java.util.*;
import java.util.regex.Pattern;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
String s = "Geeksforgeeks has Scanner Class Methods";
System.out.println("Target String:\n" + s);
Scanner scanner = new Scanner(s);
System.out.println("\nAny 5 letter plus for : "
+ scanner.findInLine(
Pattern.compile(".....for")));
scanner.close();
}
catch (IllegalStateException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Example 2: java read lines from file
Scanner sc = null;
try {
File file = new File("myfile.txt");
sc = new Scanner(file);
String line;
while (sc.hasNextLine()) {
line = sc.nextLine();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
finally {
if (sc != null) sc.close();
}