Mega Code Archive

 
Categories / Java Book / 003 Essential Classes
 

0219 Scanner

Scanner is the complement of Formatter and reads formatted input. Scanner can be used to read input from the console, a file, a string, or any source. The Scanner Constructors Scanner(File from) throws FileNotFoundException Creates a Scanner that uses the file specified by from as a source for input. Scanner(File from, String charset) throws FileNotFoundException Creates a Scanner that uses the file specified by from with the encoding specified by charset as a source for input. Scanner(InputStream from) Creates a Scanner that uses the stream specified by from as a source for input. Scanner(InputStream from, String charset) Creates a Scanner that uses the stream specified by from with the encoding specified by charset as a source for input. Scanner(Readable from) Creates a Scanner that uses the Readable object specified by from as a source for input. Scanner (ReadableByteChannel from) Creates a Scanner that uses the ReadableByteChannel specified by from as a source for input. Scanner(ReadableByteChannel from, String charset) Creates a Scanner that uses the ReadableByteChannel specified by from with the encoding specified by charset as a source for input. Scanner(String from) Creates a Scanner that uses the string specified by from as a source for input. The following code creates a Scanner that reads the file Test.txt: FileReader fin = new FileReader("Test.txt"); Scanner src = new Scanner(fin); FileReader implements the Readable interface. Thus, the call to the constructor resolves to Scanner(Readable). This next line creates a Scanner that reads from standard input, which is the keyboard by default: Scanner conin = new Scanner(System.in); System.in is an object of type InputStream. Thus, the call to the constructor maps to Scanner(InputStream). The next sequence creates a Scanner that reads from a string. String instr = "1 1.23 this is a test."; Scanner conin = new Scanner(instr);