Write a program in Java that reads each line in a standard t
Write a program in Java that reads each line in a standard txt file, reverses its lines, and
writes them to another file.
For example: if the file infile.txt contains the lines
I went down to the river.
I set down on the bank.
I tried to think but couldn\'t.
So I jumped in and sank.
and you run ReverseTxtLines infile.txt outfile.txt then oufile.txt contains
So I jumped in and sank.
I tried to think but couldn\'t.
I set down on the bank.
I went down to the river.
Note: Use exception handling to detect improper inputs.
Solution
ReverseTxtLines.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class ReverseTxtLines {
public static void main(String[] args) throws FileNotFoundException {
File file = new File(\"D:\\\\infile.txt\");
File outputfile = new File(\"D:\\\\outfile.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(outputfile);
for(int i=list.size()-1; i>=0; i--){
ps.println(list.get(i));
}
ps.flush();
ps.close();
scan.close();
System.out.println(\"outfile.txt file has been geenrated\");
}
else{
System.out.println(\"Input file does not exist\");
}
}
}
Output:
outfile.txt file has been geenrated
outfile.txt
So I jumped in and sank.
I tried to think but couldn\'t.
I set down on the bank.
I went down to the river.

