Since Scanner requires a java.io.File object, I don't think there's a way to read with Scanner only without using any java.io classes.
Here are two ways to read a file with the Scanner class - using default encoding and an explicit encoding. This is part of a long guide of how to read files in Java.
Scanner – Default Encoding
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile_Scanner_NextLine {
public static void main(String [] pArgs) throws FileNotFoundException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
try (Scanner scanner = new Scanner(file)) {
String line;
boolean hasNextLine = false;
while(hasNextLine = scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
}
}
}
Scanner – Explicit Encoding
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile_Scanner_NextLine_Encoding {
public static void main(String [] pArgs) throws FileNotFoundException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
//use UTF-8 encoding
try (Scanner scanner = new Scanner(file, "UTF-8")) {
String line;
boolean hasNextLine = false;
while(hasNextLine = scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
}
}
}