Java Create New File

Creating a new file in Java is a very easy task. In this Java tutorial, we will list down different ways to create a new file.

Read More: Create a read only file in Java

1. Create file with java.nio.file.Files

Files.write() is best way to create a new file in Java and it should be your preferred approach in future if you are not already using it.

This method writes lines of text to the created file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform’s line separator.

Method Syntax

/**
* @param   path 	- the path to the file
* @param   lines 	- an object to iterate over the char sequences
* @param   cs 		- the charset to use for encoding
* @param   options 	- options specifying how the file is opened
*
* @return  the path of the newly created file
*/

public static Path write(Path path,
     Iterable<? extends CharSequence> lines,
     Charset cs,
     OpenOption... options) throws IOException

Example 1: Check if a file already exist in Java

LinkOption.NOFOLLOW_LINKS indicates that the application should not follow symbolic links in the file system to determine if the path exists.

Path path = Paths.get("dataPath/test.text");

boolean doesFileExist =
        Files.exists(path,
            new LinkOption[]{ LinkOption.NOFOLLOW_LINKS });

Example 2: Create a new file or append to an existing file

Use StandardOpenOption to indicate if a new file has to be created or not.

List<String> lines = Arrays.asList("1st line", "2nd line");

Files.write(Paths.get("file6.txt"), lines, 
		StandardCharsets.UTF_8);

Example 3: Create a new file with default options

If we do not specify any options parameter then by default, CREATE, TRUNCATE_EXISTING, and WRITE options are use.

It does the following things:

  • Opens the file for write if exist
  • Creates the file if the file doesn’t exist
  • Opens the file for writing
  • Deletes all the file content
  • Write the new content into the file
List<String> lines = Arrays.asList("1st line", "2nd line");

Files.write(Paths.get("file6.txt"), 
				lines, 
				StandardCharsets.UTF_8,
				StandardOpenOption.CREATE, 
				StandardOpenOption.APPEND);

2. Create new file with java.io.File class

Use File.createNewFile() method to create new file. This method returns a boolean value –

  • true if the file is created successfully.
  • false if the file already exists or the operation failed for some reason.

Please note that this method will only create a file, and does not write any content into the file.

Java example to create a new create file if not exist

File file = new File("c://temp//testFile1.txt");
 
//Create the file
if (file.createNewFile())
{
    System.out.println("File is created!");
} else {
    System.out.println("File already exists.");
}

To write the content into the created file, use FileWriter class.

//Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();

3. Create new file with FileOutputStream

FileOutputStream.write() method automatically creates a new file and write content to it.

String data = "Test data";

FileOutputStream out = new FileOutputStream("c://temp//testFile2.txt");

out.write(data.getBytes());
out.close();

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

3 thoughts on “Java Create New File”

  1. Hello,

    Thanks for the good work. Would be cool if you could offer real world situations where these different implementations would be necessary.

    Thanks

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.