How to Create a New File Using Java


In this article, we show how to create a new file with Java.

With Java, we can create a new file in any directory on your computer.

In Java, a new file can be created with the createNewFile() function.

The code to create a new file in Java is shown below.

So in the file above we create a class called Createnewfile.

We then create our main method(), which is the point where execution occurs.

In the main method, we create a file object, f, and pass the parameter named "newfile.txt" into the this File object.

So at this point in the code, the File object f has the value of newfile.txt.

We then call the createNewFile() function through the if statement.

When dealing with the Java createNewFile() function, you want to deal with exception handling. This is because for various reasons, the new file may not be created. This is the case, for example, when you specify the path to a directory that doesn't exist on the computer. Maybe you put in the wrong directory or you misspelled a name of the directory . This will cause an error. The createNewFile() function need exception handling ability. So to do this, you can use a simple try or catch function, such as shown above. Without this try or catch function, the createNewFile() function will not work.

The full statement is f.createNewFile(). This creates a new file named "newfile.txt".

Since we didn't specify the path of the file, the Java program creates the new file in the current directory, the one where this Java file saves to.

If you want to specify a directory other than the current directory, then you will have to specify the complete path to the file.

Since this differs according to what operating system you are using, this is the only part of Java that becomes platform dependent.

In a Windows computer, you normally specify the drive you are using with a letter such as the C drive and then specify the path from there to the directory where you want to put the newly created file.

So if you have a file you want to create in the C:\Users\ directory, then you would write this into the string as "C:\\Users\\"

This is because "\" is an escape character; it's used for escaping strings. To show "\" in a string, you would have to put double forward slashes "\\".

And this is all that is required to create a new file in any directory using Java.

Related Resources

How to Check if a File Exists Using Java

How to Check if an Object is a File Using Java

How to Check if a File is a Directory Using Java

How to Rename a File Using Java

How to Delete a File Using Java

How to Create a New Directory Using Java

How to List All Files in a Directory Using Java

How to Read a File Using Java

How to Write Data to a File Using Java

How to Get the Size of a File Using Java

HTML Comment Box is loading comments...