Java File Writing with FileWriter
In Java, you can write text to files using FileWriter
. This is useful for saving data permanently.
Below is the Hinglish explanation line by line with code.
Java में हम FileWriter
class का use करके file में text लिख सकते हैं। यह permanent data save करने के लिए useful होता है।
नीचे line-by-line Hinglish explanation दी गई है।
Java Code Example
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, this is my first file write in Java!");
writer.close();
System.out.println("Data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output:
Hello, this is my first file write in Java!
Notes:
- If the file doesn’t exist, it will be created.
- If the file exists, it will be overwritten unless you use
FileWriter("example.txt", true)
(for appending). - Always handle IOException using try-catch.