-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandlingExample.java
More file actions
43 lines (36 loc) · 1.25 KB
/
Copy pathFileHandlingExample.java
File metadata and controls
43 lines (36 loc) · 1.25 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
/**
* Day 22 - File Handling: Reading and Writing Files
*/
import java.io.*;
import java.util.*;
public class FileHandlingExample {
public static void main(String[] args) {
System.out.println("=== File Handling ===\n");
writeToFile();
readFromFile();
}
static void writeToFile() {
System.out.println("--- Writing to File ---");
try (FileWriter writer = new FileWriter("sample.txt")) {
writer.write("Hello, World!\n");
writer.write("This is a test file.\n");
writer.write("File I/O in Java\n");
System.out.println("File written successfully");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
static void readFromFile() {
System.out.println("\n--- Reading from File ---");
try (BufferedReader reader = new BufferedReader(new FileReader("sample.txt"))) {
String line;
int lineNumber = 1;
while ((line = reader.readLine()) != null) {
System.out.println(lineNumber + ": " + line);
lineNumber++;
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}