2010. 3. 24.

File Manager

The following code is a file manager, written in the same course, which can create, append, print and copy a text file. It also can search for a string within the specified file.




import java.io.*;


public class FileMgr{
   // We use a global variable for reading from the 
   // keyboard, since all methods take user input.
   private static BufferedReader kb ; 
   public static void main( String [] args ) throws IOException {
      String kb_line ;       // user input
      char task ;            // task selected 


      // Open Keyboard for User Input
      kb = new BufferedReader(new InputStreamReader( System.in ));
      //Display Welcome Message
      System.out.println("\n================");
      System.out.println("\n  File Manager");
      System.out.println(  "================");
      // User interaction loop.
      do {
         display_menu();                      // Display Menu & Prompt User for Selection
         kb_line = kb.readLine();             // Read Users Response
         if( kb_line == null || kb_line.length() != 1 ) {
            task = '0';                       // denotes (some kinds of) invalid input
         } else {
            // Take First Character of Response (in lower case)
            task = Character.toLowerCase(kb_line.charAt(0));
         }


         // Execute Corrsponding Task
         execute_task( task );


      } while( task != 'q' && task != 'Q' );
   } // End of main


   /*******************************************************
   *  Execute the selected task
   *
   *  Argment task identifies the task.  It need not
   *   have a value that corresponds to a valid selection.
   *******************************************************/
   private static void execute_task( char t ) throws IOException {
      String userLine ;
      String fileLine ;
      BufferedReader inFile ;
      PrintWriter outFile ;


      switch( t ){


      case 'p':// Print a file


         // open file for printing 
         userLine = get_user_input("\nEnter Name of File to Print\n");
         inFile = open_input_file( userLine );
         System.out.println("=== Begin " + userLine + " ============");


         // print lines to the screen
         fileLine = inFile.readLine();
         while( fileLine != null ) {
            System.out.println( fileLine );
            fileLine = inFile.readLine();
         }
         System.out.println("=== End " + userLine + " ===========");
         inFile.close();
         break;


      case 's':           // Search a file - print lines of file containing 
                          // a given substring.


         // open file to search and get search string
         userLine = get_user_input("\nEnter Name of File to Search\n");
         inFile = open_input_file( userLine );
         userLine =  get_user_input("\nEnter String to Search for\n");


         System.out.print("=== Begin " + userLine + " lines containing ");
         System.out.println( userLine + " ============");


         // print lines containing userLine as a sub-string
         fileLine = inFile.readLine();
         while( fileLine != null ) {
            if( fileLine.indexOf( userLine, 0 ) > -1 ){
               System.out.println( fileLine );
            }
            fileLine = inFile.readLine();
         }
         inFile.close();


         System.out.print("=== End " + userLine + " lines containing ");
         System.out.println( userLine + " ===========");
         break;


      case 'c':                 // Copy a file


         // open files to copy from and to
         userLine = get_user_input("\nEnter Name of File to Copy From\n");
         inFile = open_input_file( userLine );
         userLine = get_user_input("\nEnter Name of File to Copy To\n");
         outFile = new PrintWriter( new FileWriter( userLine, true ));


         // copy lines
         fileLine = inFile.readLine();
         while( fileLine != null ) {
            outFile.println( fileLine );
            fileLine = inFile.readLine();
         }
         inFile.close();
         outFile.close();
         break;


      case 'n':


         // open new file 
         userLine = get_user_input("\nEnter Name of New File\n");
         outFile = new PrintWriter( new FileWriter( userLine ));


         System.out.print("\nBegin entering lines ");
         System.out.println("(stop by entering the line: #!stop).");


         // get lines from user and store in file
         userLine = get_user_input("");
         while( userLine != null && userLine.compareTo("#!stop") != 0 ) {
            outFile.println( userLine );
            userLine = get_user_input("");
         }
         outFile.close();
         break;


      case 'a':            // append to an existing file 


         // open desired file to append to 
         userLine = get_user_input("\nEnter Name of File to Append to\n");
         outFile = new PrintWriter( new FileWriter( userLine, true ));


         System.out.print("\nBegin entering new lines ");
         System.out.println("(Stop by entering the line: #!stop).");


         // read lines from user and store in file
         userLine = get_user_input("");
         while( userLine != null && userLine.compareTo("#!stop") != 0 ){
            outFile.println( userLine );
            userLine = get_user_input("");
         }
         outFile.close();
         break;


      case 'q':            // quit
         System.out.println("Bye!");
         break;


      default:        // handle invalid selections
         System.out.println("Your entry is not a valid selection.");
     }
  }  // End of execute_task()


   /*******************************************************
   *  Prompt the user and read a line from the keyboard.
   *  Returns the String read from the keyboard.       
   *******************************************************/
   private static String get_user_input( String prompt ) throws IOException {
      System.out.print( prompt );
      System.out.print(">>> ");
      return kb.readLine();
   }


   /*******************************************************
   *  Open a file with a given name for reading.
   *  Returns a new BufferedReader
   *******************************************************/
   private static BufferedReader open_input_file(String name) throws IOException {
      return new BufferedReader( new FileReader( name ));
   }


   /*******************************************************
   *  Display the task menu and instructions
   *******************************************************/
   private static void display_menu(){
      System.out.println("\nSelect a task from the following list by");
      System.out.println("type the first letter of the desired task ");
      System.out.println("(upper or lower case) and pressing Enter.");
      System.out.println("\nNew: create a new file");
      System.out.println("Append: append to an existing file");
      System.out.println("Print: print file to the screen");
      System.out.println("Copy: copy a file");
      System.out.println("Search: find a string in a file");
      System.out.println("Info: print program information");
      System.out.println("Quit: exit File Manager");
      System.out.print("\nTask: ");
   }
}  // End of FileMgr

댓글 없음: