Question

( IN JAVA): Write a program that reads each line in a file, and writes them...

( IN JAVA): Write a program that reads each line in a file, and writes them out in reverse order into another file. This program should ask the user for the name of an input file, and the name of the output file. If the input file contains:

Mary had a little lamb

Its fleece was white as snow

And everywhere that Mary went

The lamb was sure to go

Then the output file should end up containing:

The lamb was sure to go

And everywhere that Mary went

Its fleece was white as snow

Mary had a little lamb

Hint: You'll need to read in all the lines from the input file, store them somewhere, and then write then out in reverse order. Try to write this using methods for each piece -- the reading, and then the writing out in backwards order.

Be sure that you handle all possible exceptions appropriately -- your main() can write messages to standard output (the console) explaining to the user what any problems were. However, any methods (other than main() should not write messages to the console. This means that your main needs to make sure that all pathnames are good before calling the methods to read and write the files.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Main {

    //Method to read the lines of data and return a list
    static List<String> readLines(String name) throws IOException {
        //List to store lines
        List<String> lines = new ArrayList<>();
        //Open file for reading
        BufferedReader br = new BufferedReader(new FileReader(new File(name)));
        //Read all the lines
        String data = br.readLine();
        while (data != null) {
            lines.add(data);
            data = br.readLine();
        }
        return lines;
    }

    //Method to write lines to file
    static void writeLines(List<String> lines) throws IOException {
        //Open writer to write lines
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File("reverse.txt")));
        //Loop through list in reverse order
        for(int i=lines.size()-1;i>=0;i--){
            bw.write(lines.get(i)+"\n");
        }
        //Flush the writer
        bw.flush();
        bw.close();
    }

    public static void main(String[] args) {
        //Prompt file name
        System.out.print("Enter the file name : ");
        Scanner obj = new Scanner(System.in);
        String name = obj.nextLine();
        List<String> lines = null;
        try {
            //Read lines
            lines = readLines(name);
        } catch (IOException e) {
            System.out.println("File not found");
            return;
        }

        try {
            //Write lines
            writeLines(lines);
        } catch (IOException e) {
            System.out.println("Exception occured while writing");
        }

    }
}

OUTPUT :

input.txt

OUTPUT :

Add a comment
Know the answer?
Add Answer to:
( IN JAVA): Write a program that reads each line in a file, and writes them...
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
  • Write a program in python that reads each line in a file, reverses its lines, and...

    Write a program in python that reads each line in a file, reverses its lines, and writes them to another file. For example, if the file input.txt contain the lines: Mary had a little lamb Its fleece was white as snow And everywhere that Mary went The lamb was sure to go. and you run your Python file then output.txt contains The lamb was sure to go. And everywhere that Mary went Its fleece was white as snow Mary had...

  • Using python Question 13 (20 points) Write a function named Linestats that finds the number of...

    Using python Question 13 (20 points) Write a function named Linestats that finds the number of consonant and vowel letters on each line of a file and writes those statistics to a corresponding line of a new file, separated by a space. Definitions: A vowel letter is one of a, e, i, o, u, along with the corresponding uppercase letters..A consonant letter is not a vowel letter. The function linestats takes two parameters: 1. inFile, a string, the name of...

  • write a program in java that asks the user for a sentence, and then returns that...

    write a program in java that asks the user for a sentence, and then returns that string with the words backwards. For example: Enter a sentence! Mary had a little lamb. Your sentence backwards: lamb. little a had Mary Write a method called reverse() that accepts a sentence as a string, and then returns that string with the words backwards. Write a main() method that gets the string from the user and then displays the string backwards. demonstrate program by...

  • Write a program that writes a series of random numbers to a file. Each random number...

    Write a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 500 inclusive. 1.Use a file called randoms.txt as a input file and output file a. If you go to open the file and its not there then ask the user to create the file     and then quit 2. Ask the user to specify how many random numbers the file will hold. a.Make sure that the...

  • This Java program reads an integer from a keyboard and prints it out with other comments....

    This Java program reads an integer from a keyboard and prints it out with other comments. Modify the comments at the top of the program to reflect your personal information. Submit Assignment1.java for Assignment #1 using Gradescope->Assignemnt1 on canvas.asu.edu site. You will see that the program has a problem with our submission. Your program is tested with 4 testcases (4 sets of input and output files). In order to pass all test cases, your program needs to produce the same...

  • C++ 3. Write a program that reads integers from a file, sums the values and calculates...

    C++ 3. Write a program that reads integers from a file, sums the values and calculates the average. a. Write a value-returning function that opens an input file named in File txt. You may "hard-code" the file name, i.e., you do not need to ask the user for the file name. The function should check the file state of the input file and return a value indicating success or failure. Main should check the returned value and if the file...

  • python Write the function getSpamLines(filename) that read the filename text file and look for lines of the form &#...

    python Write the function getSpamLines(filename) that read the filename text file and look for lines of the form 'SPAM-Confidence: float number'. When you encounter a line that starts with "SPAM-Confidence:" extract the floating-point number on the line. The function returns the count of the lines where the confidence value is greater than 0.8. For example, if 'spam.txt' contains the following lines along with normal text getSpamLines('spam.txt') returns 2. SPAM-Confidence: 0.8945 Mary had a little lamb. SPAM-Confidence: 0.8275 SPAM-Confidence: 0.7507 The...

  • Capitalization JAVA In this program, you will read a file line-by-line. For each line of data...

    Capitalization JAVA In this program, you will read a file line-by-line. For each line of data (a string), you will process the words (or tokens) of that line one at a time. Your program will capitalize each word and print them to the screen separated by a single space. You will then print a single linefeed (i.e., newline character) after processing each line – thus your program will maintain the same line breaks as the input file. Your program should...

  • IN JAVA. Write a program that reads a file (provided as attachment to this assignment) and...

    IN JAVA. Write a program that reads a file (provided as attachment to this assignment) and writes the file to a different file with line numbers inserted at the beginning of each line. For example if file input is: This is a test File output should be 1. This is a test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BELOW FROM NOTEPAD FILE. This file contains lines of text to determine if you can properly read and write from a file.

  • [Java] Please test your code in the link I provide before you post your answer. The...

    [Java] Please test your code in the link I provide before you post your answer. The output should be looked like exact same as the tester. http://www.codecheck.it/files/17050415451csldwjahxt2kwn73ahd6vukt Thank you. Write a simplified application to illustrate the use of an undo button for a word processor. It keeps a history of all items and allows the user to undo the last. Write a class UndoStack. Implement using a Stack of Strings. The constructor will create an empty Stack to keep the...

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