After reading pages 330 - 336, write a program that takes two command line argum
ID: 3831619 • Letter: A
Question
After reading pages 330 - 336, write a program that takes two command line arguments which are file names. The program should read the first file line by line and write each line, in reverse order, into the second file. The program should include a "usage" method that displays the correct command line syntax if two file names are not provided.
Example: if my input file says
Hello, World!
then my output file will contain
!dlroW ,olleH
Hints:
Use CaesarCipher in section 7.3 for information on how to read the arguments in a command line.
Refer to section 7.1 for information on how to access files for reading and writing
You may copy the "usage" method from 7.3 verbatim
Refer to section 7.2.4 for information on reading lines
Write a "for" loop that reads each character, one at a time, from the end of the line to the beginning, and writes that character to the output file.
Refer to 2.5.1 for information on how to determine the length of a line
You can use charAt() (Section 2.5.5) or substring (section 2.5.6) to get the character
Explanation / Answer
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReverseFile {
public static void usage()
{
System.out.println("java ReverseFile inputFile outputFile");
}
public static void main(String[] args) throws IOException
{
if(args.length != 2)
{
usage();
return;
}
File infile = new File(args[0]);
Scanner sc = new Scanner(infile);
FileWriter outfile = new FileWriter(args[1]);
while(sc.hasNextLine())
{
String line = sc.nextLine();
for(int i = line.length()-1; i >= 0; i--)
{
outfile.write(line.charAt(i));
}
outfile.write(" ");
}
sc.close();
outfile.close();
}
}