forked from learning-zone/java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadTextFile.java
More file actions
58 lines (47 loc) · 1.62 KB
/
ReadTextFile.java
File metadata and controls
58 lines (47 loc) · 1.62 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
package strings;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
File file = new File("file.txt");
try (
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input); ) {
String line;
// Initializing counters
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int whitespaceCount = 0;
// Reading line by line from the file
while((line = reader.readLine()) != null) {
if(line.equals("")){
paragraphCount++;
}
if(!(line.equals(""))) {
characterCount += line.length();
// \\s+ is the space delimiter
String[] wordList = line.split("\\s+");
countWord += wordList.length;
whitespaceCount += countWord - 1;
// [!?.:]+ is the sentence delimiter
String[] sentenceList = line.split("[!?.:]+");
sentenceCount += sentenceList.length;
}
}
System.out.println("Total word count: " + countWord);
System.out.println("Total number of sentences: " + sentenceCount);
System.out.println("Total number of characters: " + characterCount);
System.out.println("Total number of paragraphs: " + paragraphCount);
System.out.println("Total number of whitespaces: " + whitespaceCount);
} catch (Exception e) {
System.out.println("Exception: "+e);
e.printStackTrace();
}
}
}