Java Basic Programming Help Please make sure this program ca
Java Basic Programming Help:
Please make sure this program can compile and run. Thanks!!
Write a program that reads each line in a file, reverses its lines, and writes them to another file.
For example, if the file input.txt contains the lines
Mary had a little lambIts fleece was white as snowAnd everywhere that Mary wentThe lamb was sure to go.
and you run
reverse input.txt output.txt
then output.txt contains
The lamb was sure to go.And everywhere that Mary wentIts fleece was white as snowMary had a little lamb
Solution
ReadAnsWriteReverse.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadAnsWriteReverse {
public static void main(String[] args) throws FileNotFoundException {
File file = new File(\"input.txt\");
if(file.exists()){
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(file);
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
PrintStream ps = new PrintStream(new File(\"output.txt\"));
for(int i=list.size()-1; i>=0; i--){
ps.println(list.get(i));
}
ps.flush();
ps.close();
System.out.println(\"File has been generated\");
}
else{
System.out.println(\"File does not exist.\");
}
}
}
Output:
input.txt
Mary had a little lamb
Its fleece was white as snow
And everywhere that Mary went
The lamb was sure to go.
output.txt
The lamb was sure to go.
And everywhere that Mary went
Its fleece was white as snow
Mary had a little lamb

