-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileStatistics.java
More file actions
54 lines (49 loc) · 1.48 KB
/
Copy pathFileStatistics.java
File metadata and controls
54 lines (49 loc) · 1.48 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
/* Exercise 12.13
* (Count characters, words, and lines in a file) Write a program that will count
* the number of characters, words, and lines in a file. Words are separated by
* whitespace characters. The file name should be passed as a command-line
* argument, as shown in Figure 12.13.
*
*
*/
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileStatistics {
public static void main(String[] args) {
// Start number of characters, words, and lines
int characters = 0;
int words = 0;
int lines = 0;
// Check command line parameter usage
if (args.length != 1) {
System.out.println("Usage: java FileStatistics file name");
System.exit(1);
}
// Check if source file exists
File inputFile = new File(args[0]);
if (!inputFile.exists()) {
System.out.println("Target file " + args[0] + " does not exists");
System.exit(2);
}
try (
Scanner input = new Scanner(inputFile);
) {
String inputLine;
while (input.hasNextLine()) {
inputLine = input.nextLine();
characters += inputLine.length();
lines++;
words += inputLine.split("\\w+").length;
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
// Print result
System.out.println("File " + inputFile.getName() + " has " );
System.out.println(characters + " characters");
System.out.println(words + " words");
System.out.println(lines + " lines");
}
}