Java Create File Examples

If you want to create 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 file in java.

1. Use java.io.File.createNewFile()

This is the commonly used method, you should note below tips.

  1. Create a java.io.File object with file name. It can be a file name only like "abc.txt", an absolute path like "c:/WorkSpace/test/abc.txt" or a relative path like "test1/test2/abc.txt".
  2. Call the object’s createNewFile() method to create an empty file.
  3. The method return true if the file is created successful, and false if the file already exist.
  4. If the sub directory in the path dose not exist, it will throw java.io.IOException. So you had to make sure all the sub folder in the file path is exist or created.
    java io directory not exist exception
  5. 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.
  6. If you want to make the java program platform independent, you should call 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

  1. The code is more simple than java.io.
  2. If the sub directory in the file path dose not exist, it will throw java.nio.file.NoSuchFileException. So like java.io, you should first create the sub folder then create the new file.
    java new io NoSuchFileException
READ :   Introduction To Java File Class

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 note below issues.

  1. You should download and add Apache Commons IO jar into your java project. You can read Java Copy Directory Examples for more detail.
  2. Apache commons IO will create the none exist sub folder automatically when it create 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.

	public static void main(String[] args) {
		
		CreateNewFile cnf = new CreateNewFile();
		
		//cnf.createFileUseJavaIOExample();
		
		//cnf.createFileUseJavaNewIOExample();
		
		cnf.createFileUseApacheCommonsIOExample();
	}

Download “CreateNewFileExample.zip” CreateNewFileExample.zip – Downloaded 42 times – 1 KB

(Visited 798 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.