Preview

Read Files with the Scanner Object in Java

Better Essays
Open Document
Open Document
928 Words
Grammar
Grammar
Plagiarism
Plagiarism
Writing
Writing
Score
Score
Read Files with the Scanner Object in Java
Reading Files with Scanner

Include these lines at top of program: import java.util.Scanner; import java.io.*;

Create a Scanner object to read your file:
Scanner inFile = null; try { // Create a scanner to read the file, file name is parameter inFile = new Scanner (new File("whatever.txt")); } catch (FileNotFoundException e) { System.out.println ("File not found!"); // Stop program if no file found System.exit (0); }

Methods you can use:

inFile.hasNext( ) – returns true if there is more data in the file. inFile.nextInt( ) – gets the next value in the file. This must be an integer or you will get an Input Mismatch Exception . Return data type is int. inFile.nextDouble( ) – gets the next value in the file. This must be a number or you will get an Input Mismatch Exception . Return data type is double. inFile.nextLine( ) – gets the next ENTIRE line in the file. Return data type is String. inFile.next( ) – gets the next value in the file. Return data type is String. Essentially reads the file word by word. inFile.close( ) - closes the file

There are other methods, but these will get us started!

Example programs and files follow.
EXAMPLE PROGRAMS:
// read all ints in a file import java.util.Scanner; import java.io.*; public class ReadInts
{
public static void main(String args[]) { System.out.println("***** Reading Integers from a file ****"); System.out.println(); Scanner inFile = null; try { // Create a scanner to read the file, file name is parameter inFile = new Scanner (new File("nums.txt")); } catch (FileNotFoundException e) { System.out.println ("File not found!"); // Stop program if no file found System.exit (0); }

//****************************************************** // Read the file while data still found // Print out the

You May Also Find These Documents Helpful

Related Topics