There are many ways to create a file in java. Creating a file is a very easy task. We will learn 5 different ways to Create a file.
Table of Contents
Using java.io.File class’s createNewFile method
This is simplest and oldest way to create file.Here is simple snapshot to create a file in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package org.arpit.java2blog; import java.io.File; import java.io.IOException; public class CreateFileMain { public static void main(String[] args) { try { File file = new File("c://newJava2blogfile.txt"); if (file.createNewFile()){ System.out.println("File is created!"); }else{ System.out.println("File already exists."); } } catch (IOException e) { e.printStackTrace(); } } } |
Using java.nio.file.Files from JDK 7
This is preferred way of creating file after JDK 7 on wards. Please note that it will throw FileAlreadyExistsException in case file already present.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateFileMain { public static void main(String[] args) { Path newFilePath = Paths.get("C://newJava2blogFile_jdk7.txt"); try { Files.createFile(newFilePath); } catch (IOException e) { e.printStackTrace(); } } } |
Using java.io.FileOutputStream
You can use FileOutputStream’s write method to create new file and write content to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import java.io.FileOutputStream; import java.io.IOException; public class CreateFileMain { public static void main(String[] args) throws IOException { String data = "Java writing to file"; FileOutputStream out = new FileOutputStream("c://testJava2blog.txt"); out.write(data.getBytes()); out.close(); } } |
Using guava library
Here is simple way to create file using following oneliner.
1 2 3 |
Files.touch(new File("c://newJava2blogFile_guava.txt")); |
Using Common IO library
Here is another way to create new file using Common IO library. Please note that it does nothing if file alreay exists. It is similar to touch command in linux.
1 2 3 |
Files.touch(new File("c://newJava2blogFile_commonUtil.txt")); |
That’s all about Java-create new file.