summaryrefslogtreecommitdiffstats
path: root/src/de/fhswf/in
diff options
context:
space:
mode:
Diffstat (limited to 'src/de/fhswf/in')
-rw-r--r--src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java82
-rw-r--r--src/de/fhswf/in/inf/java1/aufgabe9/WordCountTest.java40
2 files changed, 122 insertions, 0 deletions
diff --git a/src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java b/src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java
new file mode 100644
index 0000000..fcd5373
--- /dev/null
+++ b/src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java
@@ -0,0 +1,82 @@
+/**
+ *
+ */
+package de.fhswf.in.inf.java1.aufgabe9;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+
+/**
+ * A class, that counts words in files.
+ *
+ * @author $Author: $
+ * @version $Revision: $, $Date: $ UTC
+ */
+public class WordCount
+{
+
+ private TreeMap<String, Integer> wordMap = new TreeMap<>();
+
+ /**
+ * Reads the file and counts the words.
+ *
+ * @param file
+ * The file to be counted.
+ */
+ public WordCount(File file)
+ {
+ try (BufferedReader f = new BufferedReader(new FileReader(file)))
+ {
+ String line = null;
+
+ while ((line = f.readLine()) != null)
+ {
+ String[] lineArray = line
+ .split("[^\\p{IsAlphabetic}\\p{Digit}]+");
+ for (String word : lineArray)
+ {
+ // Split creates empty String, if first char is a split char.
+ if (!word.isEmpty())
+ {
+ word = word.toLowerCase();
+
+ if (wordMap.containsKey(word))
+ {
+ wordMap.put(word, wordMap.get(word) + 1);
+ }
+ else
+ {
+ wordMap.put(word, new Integer(1));
+ }
+ }
+ }
+ }
+ }
+ catch (IOException e)
+ {
+ e.printStackTrace(System.err);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public final String toString()
+ {
+ StringBuilder ret = new StringBuilder();
+
+ for (Entry<String, Integer> mapping : wordMap.entrySet())
+ {
+ ret.append(mapping.getKey() + " = " + mapping.getValue() + "\n");
+ }
+
+ return ret.toString();
+ }
+}
diff --git a/src/de/fhswf/in/inf/java1/aufgabe9/WordCountTest.java b/src/de/fhswf/in/inf/java1/aufgabe9/WordCountTest.java
new file mode 100644
index 0000000..e024529
--- /dev/null
+++ b/src/de/fhswf/in/inf/java1/aufgabe9/WordCountTest.java
@@ -0,0 +1,40 @@
+/**
+ *
+ */
+package de.fhswf.in.inf.java1.aufgabe9;
+
+import java.io.File;
+
+/**
+ * Tests the WordCount class.
+ *
+ * @author $Author: $
+ * @version $Revision: $, $Date: $ UTC
+ */
+public final class WordCountTest
+{
+
+ /**
+ * Private constructor for utility class.
+ *
+ */
+ private WordCountTest()
+ {
+ }
+
+ /**
+ * Tests the WordCount class.
+ *
+ * @param args
+ * Command line arguments.
+ */
+ public static void main(String[] args)
+ {
+ File file = new File(
+ "/home/aentfs/workspace/Java1/misc/Blatt9TestFile2.txt");
+
+ System.out.println(new WordCount(file));
+
+ }
+
+}