1. using java.io.File class
2. using java.io.FileOutputStream class
3. using java.nio.file.Files class
1. Create a file in java using java.io.File class
We will see how to create a file in java using createNewFile() method. If a file does not exist, then this method will create a file and returns true. If the file does not exist then it returns false.import java.io.*; import java.util.*; public class CreateFileUsingFileClass { public static void main( String[] args ) { try { File file = new File("C:\\newfile.txt"); /*createNewFile() will return true if file gets * created or if the file is * already present it would return false */ boolean filepresent = file.createNewFile(); if (filepresent){ System.out.println("File is created successfully"); } else{ System.out.println("File is already present at the specified location"); } } catch (IOException e) { System.out.println("Exception Occurred:"); e.printStackTrace(); } } }
2. Create a file in java using java.io.FileOutputStream class
In this method a binary file is created. This method is the preferred way prior to java 7. It is better to use NIO, which we will see next in how to create a file in java.public class CreateFileUsingFileOutputStream { public static void main (String args[]){ String data = "Test Java Hungry"; FileOutputStream out = new FileOutputStream("c://temp//testFile.txt"); out.write(data.getBytes()); out.close(); } }
3. Create a file in java using java.no.file.Files class
This should be the prefer way to create a file in java after java 7.public class CreateFileUsingNIO { public static void main (String args[]){ String data = "Test Java Hungry"; Files.write(Paths.get("c://temp//testFile.txt"), data.getBytes()); //Another way List<String> lines = Arrays.asList("1st line", "2nd line"); Files.write(Paths.get("file6.txt"), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } }
Thats all for the 3 ways to create a new file in java. If you find any other way to create a new file then please mention in comments section.