Question

FIRST: Write code that prompts the user for the name of a text file, opens that...

FIRST: Write code that prompts the user for the name of a text file, opens that file if it exists and reads the file one line at a time printing each line to the screen. You must implement the file read in a try/catch block rather than throwing the exception on the main method.

NEXT: Modify your code so that the program takes the name of two files from the command line, opens the first file if it exists for reading and the second file for writing and copies the text of the first file into the second file. As with the first step, you must implement this in a try/catch block with an appropriate error message in the catch block.

NEXT: Complete the method reverse that takes a String and returns a new String that is the original String reversed. Note that we did this method in the lab a few weeks ago, so if you have that code you can just paste it in here.

NEXT: Modify your code so that instead of printing each line to the file, it prints the reverse of each line to the output file using your reverse method.

FINALLY: Make a single change to your code so that instead of copying the file, it outputs the new file not just reversed, but with all characters transformed to uppercase letters. (HINT: Make use of String's toUpperCase() method for this).

Use the code skeleton below to start your code. Create a new project and a new class named CopyFile and paste the code skeleton into it. Then look at the course notes on File I/O to fill in what you need in the skeleton.

/**
 * Program to copy one file into another, using command line arguments
 *
 * @author YOUR NAME HERE
 * @author YOUR PARTNER NAME HERE
 * @version DATE HERE
 *
 */
import java.io.FileNotFoundException;

public class CopyFile {

    /**
     * Returns the reverse of the input String inString.
     *
     * @param inString
     *            the String to be reversed
     * @return the reverse of inString
     */
    public static String reverse(String inString) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return "";
    }

    public static void main(String[] args) {
        //TODO: Prompt the user for a filename

        //TODO: Open the file and print each line to the screen.
        //TODO: Don't forget to close the file when you are done.
        try {

        } catch (FileNotFoundException e) {

        }

    }

}

To test this program you will need a text file to read. Create a new Text File in Eclipse by going to New -> Untitled Text File. Then paste in the following text:

Jabberwocky

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

He took his vorpal sword in hand:
Long time the manxome foe he sought
So rested he by the Tumtum tree,
And stood awhile in thought.

And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One, two! One, two! and through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!"
He chortled in his joy.

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

 -- from Through the Looking-Glass, and What Alice Found There (1872).

Save this in the top-level of your project folder for this lab and name it "jabberwocky.txt". Note that it should be in your project folder and NOT in the src folder inside the project folder. When you run your program enter that file name as your input file - if your code is correct it will display the whole file to the screen. Once you have done that, modify your code so that it prompts for two filenames and makes a copy from your input file to your output file.

0 0
Add a comment Improve this question Transcribed image text
Answer #1


import java.io.BufferedReader;
import java.io.BufferedWriter;
/**
* Program to copy one file into another, using command line arguments
*
* @author YOUR NAME HERE
* @author YOUR PARTNER NAME HERE
* @version DATE HERE
*
*/
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class CopyFile {

   /**
   * Returns the reverse of the input String inString.
   *
   * @param inString
   * the String to be reversed
   * @return the reverse of inString
   */
   public static String reverse(String inString) {
       String reverse = "";
       // Iterate a loop from last index to first index of String
       // Add every char to reverse
       for (int i = inString.length() - 1; i >= 0; i--) {
           reverse += inString.charAt(i);
       }
       // Return reverse
       return reverse;
   }

   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       // Get both file names from command line
       String inputFilename = args[0];
       String outputFilename = args[1];
       try {
           BufferedReader br = new BufferedReader(new FileReader(inputFilename));
           BufferedWriter wr = new BufferedWriter(new FileWriter(outputFilename));
           String line;

           while ((line = br.readLine()) != null) {
               // Print line to screen
               // System.out.println(line.trim());

               // Write line to file
               // wr.append(line.trim()+"\n");

               // Write reverse of line to output file
               // String rev = reverse(line.trim());
               // wr.append(rev+"\n");

               // Write reverse of line and uppercase to output file
               String rev = reverse(line.trim()).toUpperCase();
               wr.append(rev+"\n");
           }
           // Close both files
           wr.close();
           br.close();
       } catch (FileNotFoundException e) {
           System.out.println(e.getMessage());
       } catch (IOException e) {
           System.out.println(e.getMessage());
       }
   }
}

OUTPUT

Add a comment
Know the answer?
Add Answer to:
FIRST: Write code that prompts the user for the name of a text file, opens that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Text book used: C Primer Plus 6th Edition, Stephen Prata Create count_ch() that will count all...

    Text book used: C Primer Plus 6th Edition, Stephen Prata Create count_ch() that will count all alphanumeric characters, all whitespace characters and all punctuation entered until the user simulates end of file from the keyboard. Also provide a total of ALL characters regardless of type. At the end, you should display 4 totals. (Also, review pages 252-254) If you copy and paste jabberwocky.txt, press enter, and then input the EOF simulation, you should have the following results... AlphaNumeric: 743, Punctuation:...

  • Language: C Write an encoder and a decoder for a modified "book cipher." A book cipher...

    Language: C Write an encoder and a decoder for a modified "book cipher." A book cipher uses a document or book as the cipher key, and the cipher itself uses numbers that reference the words within the text. For example, one of the Beale ciphers used an edition of The Declaration of Independence as the cipher key. The cipher you will write will use a pair of numbers corresponding to each letter in the text. The first number denotes the...

  • Language: C Write an encoder and a decoder for a modified "book cipher." A book cipher uses a doc...

    Language: C Write an encoder and a decoder for a modified "book cipher." A book cipher uses a document or book as the cipher key, and the cipher itself uses numbers that reference the words within the text. For example, one of the Beale ciphers used an edition of The Declaration of Independence as the cipher key. The cipher you will write will use a pair of numbers corresponding to each letter in the text. The first number denotes the...

  • Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...

    Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains a Java program. Your program should read the file (e.g., InputFile.java) and output its contents properly indented to ProgramName_Formatted.java (e.g., InputFile_Formatted.java). (Note: It will be up to the user to change the name appropriately for compilation later.) When you see a left-brace character ({) in the file, increase your indentation level by NUM_SPACES spaces. When you see a right-brace character (}), decrease your indentation...

  • JAVA Code: Complete the program that reads from a text file and counts the occurrence of...

    JAVA Code: Complete the program that reads from a text file and counts the occurrence of each letter of the English alphabet. The given code already opens a specified text file and reads in the text one line at a time to a temporary String. Your task is to go through that String and count the occurrence of the letters and then print out the final tally of each letter (i.e., how many 'a's?, how many 'b's?, etc.) You can...

  • write a python program that prompts the user for a name of a text file, opens...

    write a python program that prompts the user for a name of a text file, opens that file for reading , and tracks the unique words in a file and counts how many times they occur in the file. Your program should output the unique words and how often they occur in alphabetical order. Negative testing for a file that does not exist and an empty file should be implemented.

  • JAVA Write a program that prompts the user to enter a file name, then opens the...

    JAVA Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together...

  • Write Java code that prompts the user to enter his or her full name, then prints...

    Write Java code that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). Read an entire line as a single string. Here is an example dialogue with the user: Please enter your full name: Sammy Jankis Your name in reverse order is Jankis, Sammy

  • C++ (1) Write a program to prompt the user for an input and output file name....

    C++ (1) Write a program to prompt the user for an input and output file name. The program should check for errors in opening the files, and print the name of any file which has an error, and exit if an error occurs. For example, (user input shown in caps in first line, and in second case, trying to write to a folder which you may not have write authority in) Enter input filename: DOESNOTEXIST.T Error opening input file: DOESNOTEXIST.T...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT