CS 122   Winter 1999,  Instructor:  Jeffrey Horn

FILE INPUT and OUTPUT in Java


Read Chapter 7 on Files.


Here is code that will work!
 

//    CLASS EXERCISE on FILE I/O  in  Java
//
//       Task here is simply to print to a file the same way we
//       have been printing to the system console (namely, with the
//       "println()" method of an object like System.out).

import java.io.*;

class GenerateTopics{
        public
                static void main(String arg[]) throws Exception
                  {
 

                  //   Declare what we'll need.

                   PrintStream  mirror;
                   FileOutputStream mirrorFileStream;
                   File  mirrorFile;
 

                  //  Create objects we'll need.

                   mirrorFile = new File("mirror");
                   mirrorFileStream = new FileOutputStream(mirrorFile);
                   mirror = new PrintStream(mirrorFileStream);
 

                  //  Test them.

                   System.out.println("Look what I can print");
                   mirror.println("Look what I can write (to a file)." );

              }
 }
 



Questions (as in "test type"!):
  1. What does the code above do?
  2. Why do we need to "throw an exception"?
  3. To what class does the method "println()" belong?
  4. What if the file "mirror" already exists?
  5. What if the file did NOT already exist?
  6. What could cause an error here?


Tasks:
  1. Copy the above and run it, but make it print something different (to console and file).
  2. Re-run it with a different file name.
  3. Try instead "all in one" declarations and creations:

  4.  
      PrintStream  mirror = new PrintStream( new FileOutputStream( new File("mirror")));