Lab: Practice with Java File I/O
Objective
In this lab you will experiment with the Java Input/Output components by
implementing two programs that read input from a file and write output
to a file. You will also practice handling exceptions (IOException)
with try-catch and manipulating command-line arguments.
Setup
To get started, import the project for this lab, JavaIOExplorations,
from the JavaIOExplorations.zip file available at this
link. If you don't remember how to do this,
see the Setup
instructions
in an earlier lab.
Method
- In
CopyFileStdJava.javain thesrcfolder, complete themainmethod by pasting the code you wrote for Question 3 in the homework. In other words, your program should copy the text file given as the first command-line argument into the file given as the second command-line argument and make sure that anyIOExceptionthrown is caught and results in an error message being printed to the console (toSystem.err). - To run your program inside Eclipse and pass command-line arguments
to it, select Run > Run Configurations.... Select your Java
class (
CopyFileStdJava) from the left side column. If you do not find your class, click on the New launch Configuration button, found above the class list. In the right tabbed panel, select Arguments and, in the Program arguments box, enter the command-line arguments, separated by spaces. Click Run. Thedatafolder contains a sample input text file,importance.txt. To test your program with this input enterdata/importance.txt data/copy-importance.txtin the Program arguments box. You can use the Eclipse Compare With > Each Other feature to compare two files as you learned in a past lab. - In the Package Explorer view, copy
CopyFileStdJava.javainto a new file and name itFilterFileStdJava.java. Edit the new file so that it reads an input text file and outputs to another file only those lines of the input file that contain at least one string from a list of strings loaded from a third text file. The program expects three command-line arguments: the first is the name of the input file, the second is the name of the output file, and the third is the name of the file containing the "filter" strings, one per line. - Run your program. The
datafolder contains an example file containing some strings. Use it to filter the contents ofimportance.txtby using the command-line argumentsdata/importance.txt data/filter-importance.txt data/strings.txtand visually inspect the output file for any problems.
Additional Activities
- Modify the
CopyFileStdJava.javaprogram so that it also includes appropriate error checks on the command line arguments, e.g., missing arguments, missing input file, non-readable input file, etc. (Thejava.io.Fileclass provides helpful methods to check some of the possible errors.) - Modify the
FilterFileStdJava.javaprogram so that it also includes appropriate error checks on the command line arguments.