Question: Java Program Why is the output txt not being written in reverse? It is just writing the same text that is in my input file
Java Program
Why is the output txt not being written in reverse?
It is just writing the same text that is in my input file and I need it to be reversed.
the program needs to function as follows
| /*Write a program that reads a file containing text. Read each line and send it to the | |
| output file, preceded by line numbers. If the input file is | |
| Mary had a little lamb | |
| Whose fleece was white as snow. | |
| And everywhere that Mary went, | |
| The lamb was sure to go! | |
| then the program produces the output file | |
| 1 Mary had a little lamb | |
| 2 Whose fleece was white as snow. | |
| 3 And everywhere that Mary went, | |
| 4 The lamb was sure to go! |
My code is below.
Thanks
but it is just repeating what is in the input file
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
Get step-by-step solutions from verified subject matter experts
