-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordsAnalyzer.java
More file actions
88 lines (84 loc) · 2.82 KB
/
Copy pathWordsAnalyzer.java
File metadata and controls
88 lines (84 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.company;
import java.io.*;
import java.util.*;
public class WordsAnalyzer {
public void startWork(String in, String out){
if(readFile(in) == 1)
writeFile(out);
}
private List<Map.Entry<String, Integer>> listOfWord = new LinkedList<>();
private int count = 0;
private int readFile(String infile){
Reader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(infile));
StringBuilder stringBuilder = new StringBuilder();
HashMap<String, Integer> wordAndCount = new HashMap<>();
int symbol = reader.read();
while(symbol != -1){
if (Character.isLetterOrDigit(symbol)) {
stringBuilder.append((char) symbol);
}
else if (stringBuilder.length() != 0){
String string = stringBuilder.toString();
if (wordAndCount.containsKey(string)){
wordAndCount.put(string, wordAndCount.get(string) + 1);
}
else {
wordAndCount.put(string, 1);
}
count++;
stringBuilder.setLength(0);
}
symbol = reader.read();
}
listOfWord.addAll(wordAndCount.entrySet());
Collections.sort(listOfWord, (a, b) -> b.getValue().compareTo(a.getValue()));
}
catch (IOException e){
System.err.println("Error while reading file: " + e.getLocalizedMessage());
}
finally
{
if (null != reader)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
}
}
}
return 1;
}
private void writeFile(String outfile){
Writer writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(outfile));
for (HashMap.Entry<String, Integer> i : listOfWord) {
writer.write(i.getKey() + "; " + i.getValue() + "; " + (double) (10000 * i.getValue() / count) / 100 + "%\n");
}
}
catch (IOException e)
{
System.err.println("Error while writing file: " + e.getLocalizedMessage());
}
finally
{
if (null != writer)
{
try
{
writer.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
}
}
}
}
}