On this Java File IO tutorial, you’ll perceive how the Scanner class works with varied examples which you should utilize to your each day Java coding.
How does a Scanner work?
Principally, a Scanner breaks its enter into tokens utilizing a delimiter sample, which by default matches whitespace (blanks, tabs, and line terminators). The parsed tokens could be transformed into primitive sorts and Strings utilizing varied subsequent strategies. Right here’s the only instance of utilizing a Scanner to learn an integer quantity from the consumer:
Let’s perceive find out how to create an occasion of a Scanner and its major strategies.
How to Initialize a Java Scanner Class?
We are able to create an occasion of the Scanner class to parse a byte enter stream, a personality enter stream or a String, utilizing one of many following constructors (to call a couple of):
- Scanner(File supply): constructs a Scanner to scan the desired file utilizing the system’s default charset.
- Scanner(File supply, String charset name): constructs a Scanner to scan the desired file utilizing the desired character set.
- Scanner(InputStream supply): constructs a Scanner from a byte enter stream utilizing the system’s default charset.
- Scanner(InputStream supply, String charset name): constructs a Scanner from a byte enter stream utilizing the desired charset.
- Scanner(Readable supply): constructs a Scanner from a personality stream.
- Scanner(String supply): constructs a Scanner from a String.
Notice that these constructors throw FileNotFoundException if the desired file doesn’t exist, or IllegalArgumentException if the desired charset will not be discovered.
Java Scanner Methods:
The Scanner class supplies varied strategies for studying tokens from an enter supply. We are able to additionally use totally different delimiter and locale. Listed below are its strategies (to call a couple of):
The hasNext() method returns true if the scanner has one other token in its enter.
The hasNextXXX() method returns true if the subsequent token could be transformed to the desired sort, e.g. the hasNextInt() method returns true if the subsequent token could be transformed to an integer quantity. Listed below are such strategies (to call a couple of):
These methods throw InputMismatchException if the subsequent token cannot be transformed to the desired sort; throw NoSuchElementException if the entry is exhausted. And throw IllegalStateException if the scanner is closed. The useDelimiter(String sample)methodology specifies a delimiter totally different than the default whitespace. It’s additionally attainable to make use of an everyday expression as a delimiter for extra superior parsing.
The useLocale(Locale) methodology specifies a locale which is totally different than the system’s default locale. The skip(String pattern) method skips an input that matches the sample. This may be helpful as we don’t need to parse a sure enter.
Closing the Scanner:
We must always shut the Scanner after use by invoking its close() method. For the reason that Scanner class implements the AutoCloseable interface, we are able to use it with the try-with-resources structure to let the compiler provides the code to shut it implicitly. Next, we present you varied examples utilizing the Scanner class.
1. Using Scanner to Read User’s Input
java scanner nextline, nextInt()
A typical use of Scanner is reading input from the consumer in a command-line environment, as its nextXXX() methods are extra handy than the Console’s readLine() method which returns only String. Right here’s the example:
Here, we use the Scanner class to read a String, an integer number and a float number.
2. Using Scanner to Read Numbers from File
Run this code with a file having the following content:
And it will print the sum:
3. Using Scanner to Read a Text File line by line
nextstring java java scanner(file)
The following code uses the nextLine() method to read a text file line by line, and add all lines to a list of Strings:
4. Using Different Delimiter for Scanner
The following code uses the delimiter comma (,) to parse a CSV file:
Given the following CSV file:
5. Using Regular Expressions for Scanner
In the following code, we use regular expressions to find only Strings containing the world ‘Java’:
Here, we use a regular expression for the delimiter: [\r\n] meaning that the delimiter is new line character (either \r or \n); and the regular expression .*Java.* is to check if the input contains the word ‘Java’.Given the following text file:
6. Using Different Locale for Scanner
The following code uses a Scanner with French locale to parse numbers from a text file:
Given the following text file (in French locale):
It gives the following output (in US locale):