Reading a file with a Scanner
suggest changeReading a file line by line
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("example.txt"));
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
//do stuff
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
word by word
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("example.txt"));
while(scanner.hasNext())
{
String line = scanner.next();
//do stuff
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
and you can also change the delimiter by using the scanner.useDelimiter() method. Close the Scanner when you are done so the file is closed.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents