Skip to content

Commit b23608e

Browse files
authored
Create readtext.md
1 parent a223746 commit b23608e

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

io/readtext.md

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Read text
2+
3+
4+
```
5+
The Battle of Thermopylae was fought between an alliance of
6+
Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of
7+
Xerxes I over the course of three days, during the second Persian invasion of
8+
Greece.
9+
```
10+
11+
This is the `thermopylae.txt` file.
12+
13+
## FileReader with BufferedReader
14+
15+
```java
16+
import java.io.BufferedReader;
17+
import java.io.FileReader;
18+
import java.io.IOException;
19+
import java.nio.charset.StandardCharsets;
20+
21+
void main() throws IOException {
22+
23+
var fileName = "thermopylae.txt";
24+
25+
try (var br = new BufferedReader(new FileReader(fileName,
26+
StandardCharsets.UTF_8))) {
27+
28+
String line;
29+
while ((line = br.readLine()) != null) {
30+
31+
System.out.println(line);
32+
}
33+
}
34+
}
35+
```
36+
37+
## Word frequency
38+
39+
```java
40+
import java.io.BufferedReader;
41+
import java.io.FileReader;
42+
import java.io.IOException;
43+
import java.util.HashMap;
44+
import java.nio.charset.StandardCharsets;
45+
46+
47+
void main() throws IOException {
48+
49+
var fileName = "thermopylae.txt";
50+
var wordFreq = new HashMap<String, Integer>();
51+
52+
try (var bufferedReader = new BufferedReader(new FileReader(fileName,
53+
StandardCharsets.UTF_8))) {
54+
55+
String line;
56+
while ((line = bufferedReader.readLine()) != null) {
57+
58+
var words = line.split("\s");
59+
60+
for (var word : words) {
61+
62+
if (word.endsWith(",") || word.endsWith("?")
63+
|| word.endsWith("!") || word.endsWith(".")) {
64+
65+
word = word.substring(0, word.length()-1);
66+
}
67+
68+
if (wordFreq.containsKey(word)) {
69+
wordFreq.put(word, wordFreq.get(word) + 1);
70+
} else {
71+
wordFreq.put(word, 1);
72+
}
73+
74+
}
75+
}
76+
77+
wordFreq.forEach((k, v) -> {
78+
System.out.printf("%s -> %d%n", k, v);
79+
});
80+
}
81+
}
82+
```
83+

0 commit comments

Comments
 (0)