- It reads formatted input and converts the input into the binary form.
- Scanner can read input from the console, a file, a string, or any source that implements the Readable
interface or ReadableByteChannel.
- Scanner is packaged in java.util.
The following sequence creates a Scanner that reads the file test.txt:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
// Write output to a file.
FileWriter fout = new FileWriter("test.txt");
fout.write("2 3.4 5 6 7.4 9.1 10.5 done");
fout.close();
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
// Read and sum numbers.
while (src.hasNext()) {
if (src.hasNextDouble()) {
System.out.println(src.nextDouble());
}else{
break;
}
}
fin.close();
}
}
2.0
3.4
5.0
6.0
7.4
9.1
10.5