-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWcCommand.java
More file actions
35 lines (32 loc) · 1.13 KB
/
WcCommand.java
File metadata and controls
35 lines (32 loc) · 1.13 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
package IO;
import java.io.File;
import java.util.Scanner;
public class WcCommand extends Command {
public WcCommand() {
super("wc");
}
@Override
public void action(String[] cmd) {
if (cmd.length > 1) {
File file = new File(Main.wd, cmd[1]);
if (file.exists()) {
try (Scanner scanner = new Scanner(file)) {
int lines = 0, words = 0, chars = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lines++;
words += line.split("\\s+").length;
chars += line.length();
}
System.out.printf("Lines: %d, Words: %d, Characters: %d%n", lines, words, chars);
} catch (Exception e) {
System.out.println("Error reading file: " + e.getMessage());
}
} else {
System.out.println("File does not exist.");
}
} else {
System.out.println("No file specified. Usage: wc <file>");
}
}
}