how to read various tokens from a file using Scanner class in collections in java
Previous | Home | Next |
package r4r.co.in;
import java.util.*;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CollectionsExample {
/**
* @param args
*/
public static void main(String[] args) throws IllegalArgumentException, NoSuchElementException, IOException
{
// TODO Auto-generated method stub
try
{
int i;
String string;
boolean bool;
double dbl;
FileWriter fwrite=new FileWriter("C:\\shashi\\scannerfile.txt"); // here we have created a writable file at the "C:\\shashi\\scannerfile.txt" location
fwrite.write("Hey guys!! this is 1 true example of scanner class"); // we have write the following string to the file created
fwrite.close(); // close the writable file
FileReader fread=new FileReader("C:\\shashi\\scannerfile.txt"); // creating a FileReader object
Scanner scannerobj = new Scanner(fread); // passing the fread to Scanner class's constructor
while(scannerobj.hasNext()) // loop till scannerobj has some more tokens to read
{
if(scannerobj.hasNextInt()) // checks whether the token is an integer
{
i = scannerobj.nextInt();
System.out.println("The integer values are: "+i); // displays the integer
}
else if(scannerobj.hasNextBoolean()) // checks whether the token is a boolean value
{
bool = scannerobj.nextBoolean();
System.out.println("The boolean values are: "+bool); // displays the boolean value
}
else if(scannerobj.hasNextDouble()) // checks whether the next token is a double value
{
dbl = scannerobj.nextDouble();
System.out.println("The double values are: "+dbl); // displays the double value
}
else
{
string = scannerobj.next();
System.out.println("The string words are: "+string); // displays the string value
}
}
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
The output of the above example is given as:
The string words are: Hey
The string words are: guys!!
The string words are: this
The string words are: is
The integer values are: 1
The boolean values are: true
The string words are: example
The double values are: 4.78
The string words are: of
The string words are: scanner
The string words are: class
Previous | Home | Next |