Problem: Write a Java Program to create a new text file and write some lines to the file.
To solve this problem, we will use the File class to create a text file and FileWriter class to write few lines to it.
import java.io.*;
public class FileCreator {
public static void main(String[] args) {
// Specify the file name and path
String fileName = "example.txt";
String filePath = "C:\\Users\\User\\Documents\\";
// Create a File object
File file = new File(filePath + fileName);
try {
// Create the file if it doesn't exist
if (!file.exists()) {
file.createNewFile();
System.out.println("File created: " + fileName);
}
// Write to the file
FileWriter writer = new FileWriter(file);
writer.write("Hello World! \n");
writer.write("This is a test file. \n");
writer.write("Writing multiple lines to the file.");
// Close the file after writing
writer.flush();
writer.close();
System.out.println("Content written to the file.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Example.txt:
In this program, we create a file named “example.txt” in the specified path “C:\Users\User\Documents”, and write the lines “Hello World!” , “This is a test file.” , “Writing multiple lines to the file.” to it.
For this, we first specify the name and path for the file and use them to create a File
object.
Using this file object, we first check if the specified file already exists or not. If not, we create a new file using the createNewFile()
method.
After this we create a FileWriter
object and use it write the specified lines to the file.
Finally, after writing, we call the flush()
and close()
methods of the FileWriter
class to ensure that the written content is saved to the file.
We do all these tasks i.e. creating and writing to the file, inside the try and catch block, so that if any error occurs, we would be able to handle it without terminating the program.