In Java! Assume that the input are strings that are stored in a file.
Create a main method. The main method should expect to command
line arguments:
java TextAnalyze inputFile outputFile
The first argument is the input file. The program should open this
file and read in all the words of that file. The second argument is
the output file. The program should write to the output file: each
word of the input file (in alphabetical order), how often that word
appeared in the input file, and the percent that word was used (the
number of times the word appeared divided by the total number of
words). If the program succeeds, an appropriate message should be
printed. If there is an error, an appropriate message should be
printed. The program should not crash.
Thanks for the question, here is the complete Java class
===========================================================================================
import java.io.*;
import java.util.Map;
import java.util.TreeMap;
import java.util.Scanner;
public class TextAnalyze {
private static TreeMap<String, Integer> wordMap = new TreeMap<>();
private static int totalWordCount = 0;
public static void main(String[] args) {
String inputFile = args[0];
String outputFile = args[1];
if(args.length!=2){
System.out.println("No arguments entered");
System.exit(1);
}
try {
readAllWords(inputFile);
} catch (FileNotFoundException e) {
System.out.println("Unable to read input file: " + inputFile);
System.exit(1);
}
try {
outputAnalysisResults(outputFile);
} catch (IOException e) {
System.out.println("Unable to read output file: " + outputFile);
System.exit(1);
}
System.out.println("Program successfully executed...");
}
private static void outputAnalysisResults(String outputFile) throws IOException {
PrintWriter writer = new PrintWriter(new FileWriter(outputFile));
writer.write(String.format("%-20s%5s %10s\r\n","Word","Frequency","Percentage"));
for (Map.Entry m : wordMap.entrySet()) {
writer.write(String.format("%-20s%5d %10.2f%1s\r\n", m.getKey(), m.getValue(),
100.0 * Integer.parseInt(m.getValue().toString()) / totalWordCount,"%"));
}
writer.flush();
writer.close();
System.out.println("All words written to "+outputFile+" file...");
}
public static void readAllWords(String inputFile) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(inputFile));
while (scanner.hasNext()) {
String[] words = scanner.nextLine().split("\\s+");
totalWordCount += words.length;
for (String word : words) {
Integer c = wordMap.get(word);
wordMap.put(word, (c == null) ? 1 : c + 1);
}
}
System.out.println("All words read from the "+inputFile+" file...");
}
}
=================================================================================
In Java! Assume that the input are strings that are stored in a file. Create a...