-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandlingDemo.java
More file actions
37 lines (34 loc) · 1.29 KB
/
Copy pathFileHandlingDemo.java
File metadata and controls
37 lines (34 loc) · 1.29 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
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileHandlingDemo {
public static void main(String[] args) {
String filename = "sample.txt";
String content = "This is the content written to sample.txt.\n" +
"Java File Handling is demonstrated here.";
// Write content to file
try {
FileWriter writer = new FileWriter(filename);
writer.write(content);
writer.close();
System.out.println("Content written successfully to " + filename);
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
return;
}
// Read content from file
System.out.println("\n--- Reading from " + filename + " ---");
try {
File file = new File(filename);
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
reader.close();
System.out.println("\nFile reading completed.");
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}