Program 7 - Text Files

Goal Description Hints Passoff

Due Date - 13 Apr


Learn to do file reading and writing
 CS 142

Step 1

Write a method that accepts a file name (String), an object name (String) and a DrawObj. If the DrawObj is a Rect, Oval, or Line write out the commands from project 6 that will generate this object. For example

DrawObj aBox=new Rect(0,1,2,5);

writeObj("myObjFile.txt", "redBox",aBox);     

Might write the following to the file "myObjFile.txt"

box redBox 0 1 2 5
fill redBox 1 0 0
width redBox 0.1
line redBox 0.5 0.5 0.5

If the DrawObj is a Group, then you should write out all of the children of the group.

You only need to account for the fill color, line color, line width, translation, scale and rotation of the object. Any object other than a Rect, Oval, or Line should throw an exception and not write out anything.

Step 2

Add the command file to the command line code from project 6. This command will ask the user for a file name and will read commands from the file instead of from After reading all of the commands from the file and executing them as you did in project 6, you should again begin reading commands from the user through See the hints for how to ask the user for a file name. This should only read from .txt files. You can create .txt files either using the method from step 1 or using NotePad (in the Accessories folder for Starting programs).

Step 3

Add the command write objectName to the command line code from project 6. This will pop up a file dialog and ask the user where they want to write to. The named object will then be written out to the specified file (see helpful code below).

  • Use instanceof to test an object to see if it is a Rect, Oval, Line, or Group.
  • You can copy and paste the following code into your program. This code will help in implementing the file and write commands. It will ask the user for a file name. If the user specifies any file that is not a .txt file or if the user decides not to select a file, this will throw an exception. You will need to import javax.swing.* and* for this to compile.
  • 	private static String askUserForFileName() throws Exception
    		JFileChooser fc=new JFileChooser();
    		int rslt=fc.showSaveDialog(null);
    		if (rslt==JFileChooser.APPROVE_OPTION)
    		{	File f=fc.getSelectedFile();
    			if (f.getName().endsWith(".txt"))
    				return f.getCanonicalPath();
    				throw new Exception("file \""+f+"\" is not a .txt file");
    			throw new Exception("user did not select a file");
  • Use your code from Program 6 to do most of this. If you built your code correctly the file command simply passes a different scanner object to your method that parses all of the commands.

__ 2) Program correctly writes object descriptions to a file

__ 2) Program correctly opens a file, reads object descriptions and executes them.