If you want to create a file in java. You have three ways to do that. This article will show you how to use java.io.File.createNewFile()
, java.nio.file.Files
and org.apache.commons.io.FileUtils.write()
to create a file in java.
1. Use java.io.File.createNewFile().
This is the commonly used method, you should note the below tips.
- Create a
java.io.File
object with the file name. It can be a file name only like"abc.txt"
, or an absolute path like"c:/WorkSpace/test/abc.txt"
, or a relative path like"test1/test2/abc.txt"
. - Call the object’s
createNewFile()
method to create an empty file. - The method returns true if the file is created successfully, and false if the file already exists.
- If the subdirectory in the path does not exist, it will throw
java.io.IOException
. So you had to make sure all the subfolder in the file path exists or has been created.New file location is CI\WorkSpace\dev2qa.com\Code\dev2qa.com.txt File exist. New file location is C:\WorkSpace\dev2qa.com\Code\test\dev2qa.com.txt java.io.IOExcegtion: System can not find the path specified. at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(Unknown Source) at com.dev2qa.java.basic.file.CreateNewFile.createFileUse]avaI0(CreateNewFile.java:63) at com.dev2qa.java.basic.file.CreateNewFile.createFileUse]avaIOExample(CreateNewFile.java:39) at com.dev2qa.java.basic.file.CreateNewFile.main(CreateNewFile.java:1?) New file location is C:\WorkSpace\dev2qa.com\Code\testRelative\dev2qa.com.txt java.io.IOExcegtion: System can not find the path. at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(Unknown Source) at com.dev2qa.java.basic.file.CreateNewFile.createFileUse]avaI0(CreateNewFile.java:63) at com.dev2qa.java.basic.file.CreateNewFile.createFileUse]avaIOExamplefgfeateflgyjile.java:43) at com.dev2qa.java.basic.file.CreateNewFile.main(CreateNewFile.java:1?)
- If the file path is none absolute, it will be created at the java project root folder or current directory where you run the java class.
- If you want to make the java program platform-independent, you should call the
System.getProperty("file.separator")
to get the default os path separator and use this to construct your path. - Below is the java code example, you can see comments for more detail.
/* Use java.io.File.createNewFile(). */ public void createFileUseJavaIO(String filePath) { try { /* First check filePath variable value. */ if(filePath!=null && filePath.trim().length()>0) { File fileObj = new File(filePath); String absoluteFilePath = fileObj.getAbsolutePath(); System.out.println("NewFile location is " + absoluteFilePath); /* If not exist. */ if(!fileObj.exists()) { boolean result = fileObj.createNewFile(); if(result) { System.out.println("File " + filePath + " create success. "); } }else { System.out.println("File exist. "); } } } catch (IOException ex) { ex.printStackTrace(); } } /* Test createFileUseJavaIO(String filePath) method with three scenario. * case1 : file name only. * case2 : absolute path. * case3 : relative path. * */ public void createFileUseJavaIOExample() { /* Create with only file name. */ String fileName = "dev2qa.com.txt"; this.createFileUseJavaIO(fileName); /* Get path separator to make java code platform independent. */ String fileSep = System.getProperty("file.separator"); /* Create with absolute path. */ /* Get current working directory. */ String currDir = System.getProperty("user.dir"); /* Build a absolute path. */ String absoluteFilePath = currDir + fileSep + "test" + fileSep + "dev2qa.com.txt"; this.createFileUseJavaIO(absoluteFilePath); /* Create with relative path. */ String relativeFilePath = "testRelative" + fileSep + "dev2qa.com.txt"; this.createFileUseJavaIO(relativeFilePath); }
2. Use java.nio.file.Files.
- The code is more simple than java.io.
- If the subdirectory in the file path does not exist, it will throw
java.nio.file.NoSuchFileException
. So like java.io, you should first create the subfolder then create the new file.java.nio.file.NoSuchFileExcegtion: testRelative\dev2qa.com.txt at sun.nio.fs.WindowsException.trans1ateToIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source) at java.nio.file.Files.newByteChannel(Unknown Source) at java.nio.file.Files.createFile(Unknown Source) at com.dev2qa.java.basic.file.CreateNewFile.createFileUseJavaNewI0(§§e§teNewFile.java:113) at com.dev2qa.java.basic.file.CreateNewFile.createFileUseJavaNewIOExample(CreateHe§File.java:1B§) at com.dev2qa.java.basic.file.CreateNewFile.main(CreateNewFile.java:19)
- Below is the java code example.
/* Use java.nio.file.Files to creat. */ public void createFileUseJavaNewIO(String filePath) { try { /* First create the Path object. */ Path filePathObj = Paths.get(filePath); Path result = Files.createFile(filePathObj); System.out.println("Create " + filePath + " success. "); /* Show absolute path to see different filePath case real file location.*/ String fileAbsoultePath = result.toFile().getAbsolutePath(); System.out.println("File absolute path is " + fileAbsoultePath); }catch(Exception ex) { ex.printStackTrace(); } } /* Test createFileUseJavaNewIO(String filePath) method with three scenario. * case1 : file name only. * case2 : absolute path. * case3 : relative path. * case1 and case3 will create the file under project root folder or current java class run folder. * */ public void createFileUseJavaNewIOExample() { /* Create with only file name. */ String fileName = "dev2qa.com.txt"; this.createFileUseJavaNewIO(fileName); /* Get path separator to make java code platform independent. */ String fileSep = System.getProperty("file.separator"); /* Create with absolute path. */ /* Get current working directory. */ String currDir = System.getProperty("user.dir"); /* Build a absolute path. */ String absoluteFilePath = currDir + fileSep + "test" + fileSep + "dev2qa.com.txt"; this.createFileUseJavaNewIO(absoluteFilePath); /* Create with relative path. */ String relativeFilePath = "testRelative" + fileSep + "dev2qa.com.txt"; this.createFileUseJavaNewIO(relativeFilePath); }
3. Use Apache Commons IO (org.apache.commons.io.FileUtils.write()).
This is the simplest and easiest way to create a file in java. But you need to note the below issues.
- You should download and add Apache Commons IO jar into your java project. You can read Java Copy Directory Examples for more detail.
- Apache Commons IO will create the none exist subfolder automatically when it creates the file. No exception will be thrown.
- Below is the java code example.
/* Use Apache commons io to create new file. */ public void createFileUseApacheCommonsIO(String filePath) { try { File fileObj = new File(filePath); /* Call FileUtils.write to create the file and write some data in it. */ FileUtils.write(fileObj, "hello dev2qa.com"); System.out.println("Create " + filePath + " success. "); String fileAbsoultePath = fileObj.getAbsolutePath(); System.out.println("File absolute path is " + fileAbsoultePath); }catch(Exception ex) { ex.printStackTrace(); } } /* Test createFileUseApacheCommonsIO(String filePath) method with three scenario. * case1 : file name only. * case2 : absolute path. * case3 : relative path. * case1 and case3 will create the file under project root folder or current java class run folder. * */ public void createFileUseApacheCommonsIOExample() { /* Create with only file name. */ String fileName = "dev2qa.com.txt"; this.createFileUseApacheCommonsIO(fileName); /* Get path separator to make java code platform independent. */ String fileSep = System.getProperty("file.separator"); /* Create with absolute path. */ /* Get current working directory. */ String currDir = System.getProperty("user.dir"); /* Build an absolute path. */ String absoluteFilePath = currDir + fileSep + "test" + fileSep + "dev2qa.com.txt"; this.createFileUseApacheCommonsIO(absoluteFilePath); /* Create with relative path. */ String relativeFilePath = "testRelative" + fileSep + "dev2qa.com.txt"; this.createFileUseApacheCommonsIO(relativeFilePath); }
4. Java Main Method.
- Below is the java main method of this example, it will invoke all the above methods to demo how to create a file in java source code programmatically.
public static void main(String[] args) { CreateNewFile cnf = new CreateNewFile(); //cnf.createFileUseJavaIOExample(); //cnf.createFileUseJavaNewIOExample(); cnf.createFileUseApacheCommonsIOExample(); }