-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileReadWriteExample.java
More file actions
40 lines (32 loc) · 1.39 KB
/
FileReadWriteExample.java
File metadata and controls
40 lines (32 loc) · 1.39 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.*;
import java.util.*;
public class FileReadWriteExample {
public static void main(String[] args) {
String inputFile = "input.txt"; // Input file name
String outputFile = "output.txt"; // Output file name
int lineCount = 0;
int wordCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
lineCount++;
String[] words = line.trim().split("\\s+");
if (!line.trim().isEmpty()) {
wordCount += words.length;
}
}
// Writing results to output file
writer.write(" File Processing Result\n");
writer.write("==========================\n");
writer.write("Total Lines: " + lineCount + "\n");
writer.write("Total Words: " + wordCount + "\n");
System.out.println(" File processed successfully!");
System.out.println(" Results written to " + outputFile);
} catch (FileNotFoundException e) {
System.out.println(" Error: Input file not found!");
} catch (IOException e) {
System.out.println(" Error: An I/O exception occurred.");
}
}
}