fork download
  1. import java.io.*;
  2. class FileExample {
  3.  
  4. public static void main(String[] args) {
  5. // Define the file name
  6. String fileName = "example.txt";
  7.  
  8. // Create the file and write to it
  9. try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
  10. // Writing to the file
  11. writer.write("Hello, this is a test file.");
  12. writer.newLine();
  13. writer.write("Java makes file handling simple.");
  14. System.out.println("File created and data written successfully.");
  15. } catch (IOException e) {
  16. System.out.println("An error occurred while writing to the file.");
  17. e.printStackTrace();
  18. }
  19.  
  20. // Read from the file
  21. try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
  22. String line;
  23. System.out.println("\nReading from the file:");
  24. while ((line = reader.readLine()) != null) {
  25. System.out.println(line);
  26. }
  27. } catch (IOException e) {
  28. System.out.println("An error occurred while reading the file.");
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33.  
Success #stdin #stdout #stderr 0.09s 54856KB
stdin
Standard input is empty
stdout
An error occurred while writing to the file.
An error occurred while reading the file.
stderr
java.io.FileNotFoundException: example.txt (Permission denied)
	at java.base/java.io.FileOutputStream.open0(Native Method)
	at java.base/java.io.FileOutputStream.open(FileOutputStream.java:292)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:235)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:124)
	at java.base/java.io.FileWriter.<init>(FileWriter.java:66)
	at FileExample.main(Main.java:9)
java.io.FileNotFoundException: example.txt (No such file or directory)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110)
	at java.base/java.io.FileReader.<init>(FileReader.java:60)
	at FileExample.main(Main.java:21)