package filesample; import java.io.File; import java.util.Scanner; /* A short sample program designed to demonstrate how to use a Scanner to * read text input from a text file. The code here assumes that the there * is some data to be read from a text file named 'data.txt'. The first line * in the file is an integer that tells us how many lines of text follow * in the file. The program will read that integer and then drop into a * loop that reads that many lines of text from the file and then echoes * each line read to System.out. */ public class FileSample { public static void main(String[] args) { Scanner in = null; /* To read from a text file we construct a Scanner initialized with a * File object. Unfortunately, the Scanner's constructor may throw * an exception if the file does not exist or it can not be opened. * * To cope with the exception, we have to wrap the offending code in a * try block and set up a catch block to catch the exception and exit * the program if opening the file fails. */ try { in = new Scanner(new File("data.txt")); } catch(Exception ex) { System.out.println("An exception occured while opening the file."); System.out.println(ex.getMessage()); System.exit(1); } /* Once the file is open we can read data from it through the Scanner. * We read the integer at the start of the file and do a nextLine to * move down to the next line in preparation for reading the lines of * text. */ int numberOfStrings = in.nextInt(); in.nextLine(); // This loops reads and echos the lines of text from the file. for(int n = 0;n < numberOfStrings;n++) { String nextString = in.nextLine(); System.out.println(nextString); } } }