Java Program to Create a File and Write into the File
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Main
{
public static void main(String[] args)
{
//try blockcreateNewFile()
try
{
//Create object of File class and pass file name as parameter
File fileObj = new File("BtechGeeks.txt");
//create the file by using inbuilt createNewFile() of File class
if(fileObj.createNewFile())
{
System.out.println("File "+fileObj.getName() +" has been created");
}
//Create a writer object to write to the file & pass file name as parameter
FileWriter writerObj = new FileWriter("BtechGeeks.txt");
//Writing to the file
writerObj.write("BtechGeeks is one of the best platform to learn Java");
writerObj.close();
}
//Catch block
catch(IOException e)
{
System.out.println("Unable to complete the task");
// Print the exception occurred
e.printStackTrace();
}
//Prints on successful creation and writing in the file
System.out.println("Successfully File Created and Written into File");
}
}
Output:
Console Output:
File BtechGeeks.txt has been created
Successfully File Created and Written into File
