Write a program that takes two command line arguments which are file names. The
ID: 3832177 • Letter: W
Question
Write a program that takes two command line arguments which are file names. The program should read the first file line-by-line or character-by-character and write each line into the second file substituting numbers for letters according to the following substitution list.
a or A = 4
e or E = 3
i or I = 1
o or O = 0
t or T = 7
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! This is Leslie :) then my output file will contain H3ll0 W0rld! 7h1s 1s L3sl13 :)
Explanation / Answer
Hi,
Please see the classes below.
Please comment for any queries.
Thanks.
Formatter.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Formatter {
public static void main(String [] args){
//Getting command line args
if(args.length ==2){
String content = readFromFile(args[0]); // Reading from input File
writeToFile(args[1],content);
}
else{
System.out.println("Please pass two file names as commd line args:file1_name[space]file2_Name");
}
}
/**
* Reading from input File and getting the formatted String
* @param inFile
* @return
*/
public static String readFromFile(String inFile){
String content = "";
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(inFile);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
sCurrentLine = sCurrentLine.replace("a", "4");
sCurrentLine=sCurrentLine.replace("A", "4");
sCurrentLine=sCurrentLine.replace("e", "3");
sCurrentLine=sCurrentLine.replace("E", "3");
sCurrentLine=sCurrentLine.replace("i", "1");
sCurrentLine=sCurrentLine.replace("I", "1");
sCurrentLine=sCurrentLine.replace("o", "0");
sCurrentLine=sCurrentLine.replace("O", "0");
sCurrentLine=sCurrentLine.replace("t", "7");
sCurrentLine=sCurrentLine.replace("T", "7");
content = content +sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
/**
* Writing to output File
* @param outFile
* @param content
*/
public static void writeToFile(String outFile, String content){
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(outFile);
bw = new BufferedWriter(fw);
bw.write(content);
bw.flush();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Command line args:
input_file.txt output_file.txt
input_file.txt :
Hello, World! This is Leslie :)
output_file.txt :
H3ll0, W0rld! 7h1s 1s L3sl13 :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.