Create File and Write to the File in Java


Write a Java Program to create file and write to the file.

Click Here to View the Solution!
// importing the File class

class Main {
    public static void main(String[] args) {

        // create a file object for the current location
        File file = new File("");

        try {

            // create a new file with name specified
            // by the file object
            boolean value = file.createNewFile();
            if (value) {
                System.out.println("New Java File is created.");
            else {
                System.out.println("The file already exists.");
        catch(Exception e) {
Click Here to View the Output!
// is equivalent to
// currentdirectory/ 
File file = new File("");
Click Here to View the Explanation!
  • This program depicts the procedure of creating a file with the help of File class in java.
  • First step of execution involves importing File class.
  • Next step is to instantiate a File class object.
  • After that, file name i.e in the current location is passed to the constructor.
  • This object is assigned to a File type variable.
  • To create a new file by the name passed into the constructor, createNewFile() is called upon the file object.
  • The return value is assigned to a Boolean variable.
  • If the file does not exist already, then it is created.
  • Otherwise, a message is displayed that indicates the existence of file

%d bloggers like this: