Basic File Writing Example
This program demonstrates writing text to a file.
Problem Statement
Write a Java program that writes text into a file.
Source Code
| 1 | import java.io.*; |
| 2 | public class FileWriteExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq File Write Example"); |
| 5 | try(FileWriter fw=new FileWriter("output.txt")) { |
| 6 | fw.write("Eduinq File Handling Example\n"); |
| 7 | fw.write("Writing to a file successfully"); |
| 8 | } catch(IOException e) { |
| 9 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 10 | } |
| 11 | } |
| 12 | } |
Program Output
Eduinq File Write Example (File output.txt contains:) Eduinq File Handling Example Writing to a file successfully
Explanation
File writing uses FileWriter to write text data. - Try-with-resources ensures safe closure of file streams. - Exception handling prevents crashes if file path is invalid. - In enterprise systems, file writing is used for logs and reports. Conclusion: Shows basic file writing in Java.