Create File and Write to the File in Java

Exercise:

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

Click Here to View the Solution!
// importing the File class
import java.io.File;

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

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

        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) {
            e.getStackTrace();
        }
    }
}
Click Here to View the Output!
// javaFile.java is equivalent to
// currentdirectory/JavaFile.java 
File file = new File("JavaFile.java");
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: