Question: 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!