Java program to create file and write to the file

Here's a Java program to create a file and write to it:

refer t‮i:o‬giftidea.com
import java.io.FileWriter;
import java.io.IOException;

public class CreateAndWriteToFile {
    public static void main(String[] args) {
        try {
            // Create a FileWriter object to write to a file
            FileWriter fileWriter = new FileWriter("filename.txt");
            
            // Write some text to the file
            fileWriter.write("Hello, world!");
            fileWriter.write("\n");
            fileWriter.write("This is a Java program.");
            
            // Close the FileWriter object
            fileWriter.close();
            
            System.out.println("File created and text written to it.");
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This program uses a FileWriter to create a new file or overwrite an existing one. The FileWriter object is created with the name of the file that we want to create or write to. In this example, we are creating a new file called "filename.txt".

We then use the write() method of the FileWriter object to write some text to the file. We have added two lines of text to the file using the write() method. Note that we have added a newline character (\n) between the two lines to ensure that they appear on separate lines in the file.

After we are done writing to the file, we close the FileWriter object using the close() method. It's always a good practice to close any input/output stream objects after we are done using them.

The program then prints a message to the console indicating that the file has been created and text has been written to it.

Note that in this program, we have used a try-catch block to handle any IOException that might occur while writing to the file. It's always a good idea to handle exceptions when reading/writing files to ensure that your program doesn't crash if there is an error.