import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class badCounter {
public static Map<String, Integer> mapOfBadNames = new HashMap<>();
protected void doProcessing(String filePath) throws IOException {
try {
FileInputStream fis = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while((br.readLine())!=null){
processWords(br.readLine());
}
br.close();
fis.close();
} catch (IOException | NullPointerException ex) {
System.out.println(ex.getMessage());
}
}
private void processWords(String line) {
Arrays.stream(line.split(" "))
.map(String::trim)
.forEach(word -> {
if(mapOfBadNames.containsKey(word)){
mapOfBadNames.put(word, mapOfBadNames.get(word)+1);
} else{
mapOfBadNames.put(word, 1);
}
});
}
public void writeResultToFile(String path) throws IOException {
try {
PrintWriter out = new PrintWriter(path);
out.println("word,frequency");
for(Map.Entry<String, Integer> entry : mapOfBadNames.entrySet()){
out.println(entry.getKey() + "," + entry.getValue());
}
out.close();
} catch (NullPointerException | IOException ex) {
throw new RuntimeException("Error writing to file", ex);
}
}
public boolean isEverythingFine() {
return true;
}
public static void main(String[] args) {
badCounter bcn = new badCounter();
try {
bcn.doProcessing("bad_input.txt");
bcn.writeResultToFile("result.csv");
bcn.doProcessing("bad_input1.txt");
bcn.writeResultToFile("result1.csv");
} catch (IOException ex) {
System.out.println("Something went wrong");
}
}
}