Java program to write data into a file:
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
// Specify the file path
String filePath = "output.txt";
try {
// Create a FileWriter object with the specified file path
FileWriter writer = new FileWriter(filePath);
// Write data into the file
writer.write("Hello, World!\n");
writer.write("This is a Java program to write into a file.\n");
// Close the FileWriter object
writer.close();
System.out.println("Data has been written into the file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}
```
Explanation:
1. We specify the file path where we want to write the data. In this example, the file will be created in the same directory as the Java program.
2. Inside the `try` block, we create a `FileWriter` object with the specified file path.
3. We use the `write()` method of the `FileWriter` object to write data into the file. We can call this method multiple times to write multiple lines of data.
4. After writing the data, we close the `FileWriter` object using the `close()` method.
5. If an exception occurs during the file writing process, we catch the `IOException` and print the error message and stack trace.