-
Notifications
You must be signed in to change notification settings - Fork 0
/
wc.java
executable file
·36 lines (33 loc) · 1.37 KB
/
wc.java
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
import java.io.*;
import java.nio.file.*;
class wc {
public static void main(String[] args) throws IOException {
long lineCount = 0, wordCount = 0, charCount = 0;
char[] cbuf = new char[16 * 1024];
InputStream is = args.length == 0 ? System.in : Files.newInputStream(Paths.get(args[0]));
try (Reader reader = new InputStreamReader(is)) {
boolean prevWhitespace = true;
int count;
while ((count = reader.read(cbuf)) >= 0) {
for (int i = 0; i < count; i++) {
char charVal = cbuf[i];
charCount++;
if (charVal == '\n') {
lineCount++;
prevWhitespace = true;
} else if (isWhitespace(charVal)) {
prevWhitespace = true;
} else if (prevWhitespace) {
wordCount++;
prevWhitespace = false;
}
}
}
}
String fileName = args.length > 0 ? " " + args[0] : "";
System.out.printf("%6d %6d %6d %s\n", lineCount, wordCount, charCount, fileName);
}
private static boolean isWhitespace(int charVal) {
return charVal == ' ' || charVal == '\t' || charVal == '\r' || charVal == '\f';
}
}