Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Assignment4S19;
- import java.io.File;
- import java.util.Formatter;
- import java.util.Iterator;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.Scanner;
- import javax.swing.JFileChooser;
- public class CountWords {
- static void countEachWord(File file, Map<String, Integer> words) {
- try {
- Scanner input = new Scanner(file);
- while (input.hasNext()) {
- String next = input.next();
- next = next.toLowerCase();
- Integer count = words.get(next);
- if (count != null)
- count++;
- else
- count = 1;
- words.put(next, count);
- }
- input.close();
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- public static void main(String[] args) {
- try {
- Map<String, Integer> words = new LinkedHashMap<String, Integer>();
- JFileChooser chooser = new JFileChooser();
- int num = chooser.showOpenDialog(null);
- File file = chooser.getSelectedFile();
- Scanner input2 = new Scanner(file);
- countEachWord(file, words);
- String filename = file.getName();
- System.out.println(filename);
- String outputFileName = filename.substring(0, filename.length() - 4);
- outputFileName += "_Out.txt";
- File outputFile = new File(outputFileName);
- if (outputFile.createNewFile()) {
- System.out.println("File created.");
- } else {
- System.out.println("File already exists.");
- }
- Formatter formatter = new Formatter("C:\\CST8284\\output\\"+outputFile);
- Iterator it = words.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry pair = (Map.Entry) it.next();
- formatter.format("%s\t%d%n", pair.getKey(), pair.getValue());
- it.remove();
- }
- formatter.close();
- input2.close();
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement