Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Java program question I need to write a program that reads each line in a file, reverses its lines, and writes them to another file.

Java program question

I need to write a program that reads each line in a file, reverses its lines, and writes them to another file.

For example if input file contains " hello this is a line"

"this is another line"

the output txt file would contain "this is another line"

"hello this is a line"

An example of what i have is below but it is just writing the same text to the output file that is in the input file

package testing;

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner;

public class Reverse { static String INPUT_FILE_NAME = "C:\\Users\\sarah\\OneDrive\\Documents\\input.txt"; static String OUTPUT_FILE_NAME = "C:\\Users\\sarah\\OneDrive\\Documents\\output.txt"; public static void main(String[] args) throws IOException { ArrayList listLines = ReadFile(); System.out.println("Before Reverse Order, ArrayList Contains : " + listLines); Collections.reverse(listLines); System.out.println("Before Reverse Order, ArrayList Contains : " + listLines); WriteFile(listLines); } public static void WriteFile(ArrayList listLines) throws IOException { try { try (BufferedWriter out = new BufferedWriter(new FileWriter(OUTPUT_FILE_NAME))) { for (int i = 0; i < listLines.size(); i++) { out.write(listLines.get(i).toString()); out.newLine(); } } } catch (Exception exp){ System.err.println(""+ exp.getMessage()); } } public static ArrayList ReadFile() throws IOException { ArrayList listLines = new ArrayList(); try (BufferedReader br = new BufferedReader(new FileReader(INPUT_FILE_NAME))) { String line = br.readLine(); while (line != null) { listLines.add(line); line = br.readLine(); } } catch(Exception exp){ System.err.println(""+ exp.getMessage()); } return listLines; } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions