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

Answer:

Sure.


Line Trimmer Program

// Create a new text file, a copy of the input text file
// but with white space trimmed from the beginning and
// ends of lines.

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

public class FileTrimmer
{
  public static void main (String[] args)  
  { 
    Scanner input = null ;
    PrintWriter output = null ;
    Scanner user = null ;
    String  inputFileName, outputFileName;
 
    // Open Files
    try
    {
      // create Scanner for user input
      user = new Scanner( System.in );
      
      // prepare the input file
      System.out.print("Input File Name: ");
      inputFileName = user.nextLine().trim();
      File file = new File( inputFileName );      
      input = new Scanner( file );      

      // prepare the output file 
      System.out.print("Output File Name: ");
      outputFileName = user.nextLine().trim();
      output = new PrintWriter( outputFileName );  
    }
    catch ( IOException iox )
    {
      System.out.println("Problem Opening Files");
      System.out.println( iox.getMessage() );
      if ( input  != null ) input .close();
      if ( output != null ) output.close();
      return;
    }
    
    // processing loop
    try
    {
      // for each line of input
      while( input.hasNextLine() )    
      {
        String line = input.nextLine() ; 
        output.println( line.trim() );
      } 
    }
    catch ( Exception ex )
    {
      System.out.println("Problem with file I/O");
      System.out.println( ex.getMessage() );
    }
    finally
    {
      // close the files
      if ( input  != null ) input .close();
      if ( output != null ) output.close();
    }
    
  }
}

This program asks the user for an input file name and an output file name. After opening the files, the program reads in a line, trims whitespace off the ends, and writes the line to the output file.

The program uses two try/catch structures in sequence. It could be written with one big try block, but sometimes it is nice to keep the blocks small so errors are localized.

Here is an example input file. The display comes from Notepad++ which can display whitespace characters. (Click on the symbol in the tool bar that looks like a paragraph symbol: ¶) This is often very useful.

text file with whitespace at ends of lines

Here is the output file:

text file with whitespace at ends of lines removed

QUESTION 11:

Could a try/catch structure be nested inside one of the blocks of a try/catch structure?


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