Creating a file on disk

  • Eclipse: Oxygen
  • Java: 1.8

This tutorial is about creating a text or creating a file on disk. This can be done by importing the file library. Here you can study all the commands related to the creation of files and their location on the disk. It also deals with the exceptions thrown after file creation. The concept of the absolute and relative path is also shown here.

Following constructor takes a file object to create the file. First, we create a file object using File() method as follows:

File file = new File(“StudyEasy.txt”);

Once you have an object in hand, then there is a list of helper methods, we select the file.createNewFile() method. This method is used to create a new empty file.

When we create a new file we need to handle the exception. Here we make use of Add throws declaration that throws when it’s not able to create the file.

Here we have not given any path as a result “StudyEasy.txt” is created inside the project file. Hence this particular file name is related to the project.

Here is the program that demonstrates to create a file inside the folder. If you used this type of path on a windows machine that starts with (/ or \\), the path will be interpreted as relative to the current project.

This program demonstrates the absolute path.

Contributed by: Poonam Tomar

Full stack Java Developer

   Buy me a coffee!



Download file

Leave a Reply

Notify of
Close Menu