Creating files in Java is a basic operation, everyone must know. So, in this tutorial, I just synthesized the ways that we can create a file in Java. Maybe it is useful for beginners of Java programming.
First, I have to mention the File object. This object has been in Java since the JDK 1.0 release, which means it’s been a long time.
In this object, we have a method for creating a file, called createNewFile().
When you use this method, after execution it returns back to you a boolean value. If we were able to create the file without any problems then the return value would be true otherwise if something went wrong, the return value would be false.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class FileCreation { public static void main(String[] args) { File file = new File("E:\\note.txt"); try { if (file.createNewFile()) { System.out.println("File created successfully"); } } catch (IOException e) { e.printStackTrace(); } } } |
The second method we can use to create a file in Java is: to use the Files object, which is introduced from Java 7.
The static method createFile() in the Files object is used to create any file.
1 2 3 4 5 6 7 8 9 10 11 |
public class FileCreation { public static void main(String[] args) { try { Path path = Paths.get("E:\\test.txt"); Files.createFile(path); } catch (IOException e) { e.printStackTrace(); } } } |
In that, the Path object holds the information about the path of the file which we want to create.