Colorado State University

Recitation R9 - File Input & Output
Summer 2016

CS160: Foundations in Programming


Example of reading a file

try {
	// make sure TA explains this line and the try/catch block
	Scanner fileReader = new Scanner(new File(args[0]));
	
	// Examples: (not meant to be run as a program)
	String example1a = fileReader.next();
	String example1b = fileReader.nextLine();
	double example2 = fileReader.nextDouble();
	int example3 = fileReader.nextInt();
	char example4 = fileReader.next().charAt(0);
	
	if (fileReader.hasNext()) {
		// I can grab a string token safely
		String example5 = fileReader.next();
	}
	
	if (fileReader.hasNextDouble()) {
		// I can grab a double safely
		double example6 = fileReader.nextDouble();
	}
	
	if (fileReader.hasNextInt()) {
		// I can grab a int safely
		int example7 = fileReader.nextInt();
	}
	
	fileReader.close();
	
} catch (FileNotFoundException e) {
	System.out.println("ERROR!");
	System.exit(0);
}

© 2015 CS160 Colorado State University. All Rights Reserved.