Scanner class to read the content of a file in Java
Fri Sep 10 08:16:51 UTC 2010
You could use a combination of InputStream and readers, but starting from Java 1.5+ you can simply use the useful Scanner class as shown here:
Scanner scanner = new Scanner(file).useDelimiter("\\Z");
String fileContent = scanner.next();
scanner.close();
System.out.println(fileContent);
To read the same file but in a line per line basis, replace the previous code with this one:
Scanner scanner = new Scanner(file);
String line = null;
while((line = scanner.nextLine()) != null) {
System.out.println(line);
}
scanner.close();
The delimiter "\\Z" points to the end of file.
Keywords: java, scanner, file, content
