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

Answer:

This will slow down disk I/O.


File Name from User Input

The next example program writes to a disk file named by the user. The trim() method removes leading and trailing spaces from the user data.

Two try{} blocks are used. The first catches errors in creating the file; the second catches errors in writing data to it.


import java.io.*;
import java.util.Scanner;

class CreateFile
{
  public static void main ( String[] args ) 
  {

    // Get filename and create the file
    FileWriter writer = null;
    Scanner scan = new Scanner( System.in );
    String fileName = "";
    System.out.print("Enter Filename-->");                    // Ask for the file name
    
    try
    {
      fileName = scan.next();                                  // Get the file name
      writer = new FileWriter( fileName );                     // Create the file
    }
    catch  ( IOException iox )
    {
      System.out.println("Error in creating file");            // On failure, write error message
      return;                                                  // Return 
    } 
      
    // Write the file.
    try
    {  
      writer.write( "Behold her, single in the field,\n"  );   // Write text to the file
      writer.write( "Yon solitary Highland Lass!\n"  );  
      writer.write( "Reaping and singing by herself;\n" );  
      writer.write( "Stop here, or gently pass!\n"  );  
      writer.close();                                          // Close the file
    }
    catch ( IOException iox )
    {
      System.out.println("Problem writing " + fileName );     // On failure, write error message
    }
  }
}

QUESTION 12:

What happens (in this program) if the close() method fails?