go to previous page   go to home page   go to next page

Answer:

Yes.


File.exists() method

The File.exists() method returns true if the file corresponding to the File object already exists. It can be used to avoid accedentally destroying a file. First you need to create a File object. Remember that creating a File does not actually create the corresponding disk file.

File outFile = new File("myOutput.txt" );
if ( outFile.exists() ) throw new IOException( "File already exists");
output = new PrintWriter( outFile );

The constructor for IOException can be given a message to include in the IOException object. This is true of all Exception constructors.

The constructor for PrintWriter can be give a File object rather than a string file name.


import java.io.*;

public class WriteTextFile 
{

  public static void main ( String[] args ) 
  {
    PrintWriter output = null;
    
    try
    {
      File outFile = new File("myOutput.txt" );
      if ( outFile.exists() ) throw new IOException( "File already exists");
      
      output = new PrintWriter( outFile );
      output.println( "The world is so full"  );  
      output.println( "Of a number of things,"  );  
      output.println( "I'm sure we should all" );  
      output.println( "Be as happy as kings."  );  
    }
    catch ( IOException iox )
    {
      System.out.println( "Problem opening file:" );
      System.out.println( iox.getMessage() );
    }
    
    if ( output != null ) output.close();
  }
}


The revised program catches IOExceptions and writes out a helpful message. If the file was opened, the program closes it. But the program is careful not to close a file that is not open.

Here is a run of the program.

C:\JavaSource> java WriteTextFile
Problem opening file:
File already exists

QUESTION 10:

Could the names of the input file and the output file come from the user?


go to previous page   go to home page   go to next page