In this post, we are going to learn create text file from java with example
In this example, we are going to use File.java to create file
please make sure your code is under try catch block. Because there is chance to getting IOException
Prerequisites
- Java installed
- your program should have access to create file on the path
Syntax
file.createNewFile();
Example
import java.io.File;
public class CreateFileExample {
public static void main(String[] args) {
try {
File file = new File("C://temp//sample.txt");
// .exists Method check if file already exists on the path
if (!file.exists()) {
// Below line will create file sample.txt on C://temp// folder
file.createNewFile();
System.out.println("File created succesfully !!");
} else {
System.err.println("File already exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
File created succesfully !!
if file already exists in the C://temp folder we will get below output
File already exists
Access denied
Make sure you have access from java to create file on the folder else you will get access denied exception like below
java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at com.geeks.example.CreateFileEaxmple.main(CreateFileEaxmple.java:11)
Github
Related Articles
how to read a file from java with example