Java File Handling
Language: Java
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("story.txt");
writer.write("Once upon a time,\n");
writer.write("a program learned to write files.");
writer.close(); // important: flushes and releases the file
System.out.println("Wrote to the file successfully.");
} catch (IOException e) {
System.out.println("Could not write: " + e.getMessage());
}
}
}Output
Click Run to execute this code.