-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ7.java
More file actions
40 lines (37 loc) · 1.21 KB
/
Q7.java
File metadata and controls
40 lines (37 loc) · 1.21 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
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Q7 {
private static int countWords(String line)
{
if (line == null || line.isEmpty())
{
return 0;
}
String[] words = line.split("\\s+");
return words.length;
}
public static void main(String[] args) {
String inputFilePath = "Q6.txt";
String outputFilePath = "Q7_out.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
FileWriter writer = new FileWriter(outputFilePath))
{
String line;
int wordCount = 0;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
wordCount += countWords(line);
}
System.out.println("Total words in the file: " + wordCount);
writer.write("Total words in the file: " + wordCount);
}
catch
(IOException e)
{
System.out.println("An error occurred while reading/writing the file: " + e.getMessage());
}
}
}