e!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> CISC 1115 Files

CISC 1115
Introduction to Programming Using Java
Files


Reading from the Text

  • The text does not discuss files.
  • Files

    Files vs Streams

    Until now, we've only dealt with System.out and System.in which are called stream. Files on the other hand are more permanent data sources that reside on disk; they can be opened repeatedly.

    Files and Scanner

    Notes

    FileNotFoundException at Compilation and Execution

    P05.1 Rounder Write a program that illustrates the Math.round method by reading in a header value (i.e., number of data items to read in) from the file data.text followed by that number of floating point numbers (doubles). For each number read in, print out the number and it's rounded value using Math.round.
    Code
    

    import java.io.*; import java.util.*; public class Rounder { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("data.text")); int howMany = scanner.nextInt(); for (int i = 1; i <= howMany; i = i + 1) { double d = scanner.nextDouble(); System.out.println(d + " rounds to " + Math.round(d)); } } }

    data.text
    

    6 3.2 5.7 4.5 9.0 12 16.4

    Stdout
    

    3.2 rounds to 3 5.7 rounds to 6 4.5 rounds to 5 9.0 rounds to 9 12.0 rounds to 12 16.4 rounds to 16

    The next and nextLine Methods

  • Thus, if one has a data item containing blanks — for example a street address:
    2900 Bedford Avenue
    		
    or a full (i.e., first and last) name:
    Gerald Weiss
    		
    the individual elements (e.g. the house number (2900), street name (Bedford), street type, (Avenue, first name (Gerald), and last name (Weiss) could be Note:

    Prompting for the Name of the File — Multiple Scanners

    P5.2 Finder Write a program that prompts the user for a file name and an integer, and if the integer appears as one of the three numbers in the corresponding file, the program outputs *** Found it!;
    Code
    

    import java.io.*; import java.util.*; public class Finder { public static void main(String [] args) throws Exception { Scanner keyboard = new Scanner(System.in); System.out.print("Which file would you like to search? "); String filename = keyboard.next(); System.out.print("Which number would you like to find? "); int theNumber = keyboard.nextInt(); Scanner dataFile = new Scanner(new File(filename)); int n = dataFile.nextInt(); for (int i = 1; i <= n; i = i + 1) { int num = dataFile.nextInt(); if (theNumber == num) System.out.println("*** Found it!"); } } }

    Stdin
    

    data.text 4

    data.text
    

    3 2 4 6

    Stdout
    

    Which file would you like to search? Which number would you like to find? *** Found it!

    Interactive Session

    Here is a sample execution of the program.
    User input is in bold.
    Which file would you like to search? data.text
    Which number would you like to find? 4
    *** Found it!

    Writing Output to a File — the PrintStream Class

    P05.3 Rounder

    Rewrite P05.1 so that the output is written to the file data.output (rather than the screen)

    Code
    

    import java.io.*; import java.util.*; public class Rounder { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("data.text")); PrintStream ps = new PrintStream("data.output"); int howMany = scanner.nextInt(); for (int i = 1; i <= howMany; i = i + 1) { double d = scanner.nextDouble(); ps.println(d + " rounds to " + Math.round(d)); } } }

    data.text
    

    6 3.2 5.7 4.5 9.0 12 16.4

    data.output
    

    3.2 rounds to 3 5.7 rounds to 6 4.5 rounds to 5 9.0 rounds to 9 12.0 rounds to 12 16.4 rounds to 16

    P05.4 FileCopier

    Write a program that prompts the user for the name of an existing file and the name of a second file to which the contents of the first file should be copied. The existing file contains a header file (an integer) followed by that number of doubles.

    Code

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    import java.util.Scanner;
    
    public class FileCopier {
    	public static void main(String [] args) throws FileNotFoundException {
    		Scanner keyboard = new Scanner(System.in);
    
    		System.out.println("File to copy from: ");
    		String infilename = keyboard.next();
    
    		System.out.println("File to copy to: ");
    		String outfilename = keyboard.next();
    
    		Scanner infile = new Scanner(new File(infilename));
    		PrintStream outfile= new PrintStream(outfilename);
    
    		int numberOfValues = infile.nextInt();
    		outfile.println(numberOfValues);			// have to copy the header as well
    		outfile.println();						// blank line to separate the header from the actual data
    
    		for (int i = 1; i <= numberOfValues; i = i + 1) {
    			double num = infile.nextDouble();
    			outfile.println(num);
    		}
    
    		infile.close();
    		outfile.close();
    
    		System.out.println(numberOfValues + " values copied from " + infilename + " to " + outfilename);
    	}
    }
    
    Notes
    • There are four files/streams in play here:
      • stdin (the keyboard), represented by System.in
      • stdout (the screen) reoresented by System.out
      • the (existing, input) file whose name is contained in the variable infilename, and represented by the variable infile
      • the (output) file whose name is contained in the variable outfilename, and represented by the variable outfile
    • In addition to the actual data, we must also write out the header value at the beginning of the file; we also write out a blank line to separate the header from the actual (double) data values (see below).
      • This is actually a good place for a comment, simply reading the code doesn't convey what the intent of the printing of the header and subsequent blank line
    • The programmer who created this class decided to insert a blank line after the header value, and then place the actual data (the doubles) each on a separate line.
    oldfile.data
    5
    12.1   6.7   3.5   9   45.2
    
    Notes
    • The creator of this file elected to place all the actual data (the double values) on the same line
      • This works as nextDouble simply reads in values expecting them to be doubles, and stops reading characters when it encounters whitespace, be it a newline, a tab, or a blank
    stdin (keyboard)
    oldfile.data
    newfile.text
    
    Notes
    • Files with different suffixes/extension (.data vs .text) are used here just to make sure it was understood that not all data files end in .text or .data
    newfile.text
    5
    
    12.1
    6.7
    3.5
    9.0
    45.2
    
    Notes
    • The format of the data in this file is different than the input file, so in some sense, the copy is faulty. However, with respect to the way we read it in. i.e., using nextDouble, this format would work if it was the input file to this program.
    stdout
    File to copy from: 
    File to copy to: 
    5 values copied from oldfile.data to newfile.text
    

    The PrintWriter Class

    For technical reasons beyond the scope of this class (or at least for now), there is a second class — PrintWriter — that provides print and println that operate identically (as far as we are concerned to those of the PrintStream class. And for equally obscure reasons, CodeLab exercises on files request the use of PrintWriter rather than PrintStream.

    Files used in Lecture 5

    Lab for Lecture 5