Java – How to create a new file | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

There are various ways in which you can create a new file in Java. The two most recommended way of creating new files.

Create New file using Java NIO (Recommended) – JDK 7+

You can use Files.createFile(path) method to create a new File in Java :

package com.example.java.programming.file;

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author code.factory
 *
 */
public class CreateNewFile {
	public static void main(String... args) {
		Path filePath = Paths.get("./test.txt");

		try {
			// Create a file at the specified file path
			Files.createFile(filePath);
			System.out.println("File created successfully!");

		} catch (FileAlreadyExistsException e) {
			System.out.println("File already exists");
		} catch (IOException e) {
			System.out.println("An I/O error occurred: " + e.getMessage());
		} catch (SecurityException e) {
			System.out.println("No permission to create file: " + e.getMessage());
		}
	}
}

Create New File with missing parent directories using Java NIO

There are scenarios in which you may want to create any missing parent directories while creating a File. You can use Files.createDirectories(path) function to create missing parent directories before creating the file.

package com.example.java.programming.file;

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author code.factory
 *
 */
public class CreateNewFile {
	public static void main(String... args) {
		Path filePath = Paths.get("files/file/test.txt");
		
		try {
			// Create missing parent directories
			if (filePath.getParent() != null) {
				Files.createDirectories(filePath.getParent());
			}

			// Create a file at the specified file path
			Files.createFile(filePath);
			System.out.println("File created successfully!");

		} catch (FileAlreadyExistsException e) {
			System.out.println("File already exists");
		} catch (IOException e) {
			System.out.println("An I/O error occurred: " + e.getMessage());
		} catch (SecurityException e) {
			System.out.println("No permission to create file: " + e.getMessage());
		}
	}
}

Create New File in Java using java.io.File class – JDK 6+

You can also use the File.createNewFile() method to create a new File in Java. It returns a boolean value which is –

  • true, if the file does not exist and was created successfully
  • false, if the file already exists
package com.example.java.programming.file;

import java.io.File;
import java.io.IOException;

/**
 * @author code.factory
 *
 */
public class CreateNewFile {
	public static void main(String... args) {
		File file = new File("./test.txt");

		try {
			// Create the file in the filesystem
			boolean success = file.createNewFile();

			if (success) {
				System.out.println("File created successfully!");
			} else {
				System.out.println("File already exists!");
			}
		} catch (IOException e) {
			System.out.println("An I/O error occurred: " + e.getMessage());
		} catch (SecurityException e) {
			System.out.println("No sufficient permission to create file: " + e.getMessage());
		}
	}
}

Create New File along with missing parent directories with java.io.File class

If you want to create missing parent directories while creating a file, then you can explicitly create the directories by calling file.getParentFile().mkdirs() method :

package com.example.java.programming.file;

import java.io.File;
import java.io.IOException;

/**
 * @author code.factory
 *
 */
public class CreateNewFile {
	public static void main(String... args) {
		File file = new File("files/file//test.txt");

		try {
			// Create missing parent directories
			if (file.getParentFile() != null) {
				file.getParentFile().mkdirs();
			}

			// Create the file
			boolean success = file.createNewFile();

			if (success) {
				System.out.println("File created successfully!");
			} else {
				System.out.println("File already exists!");
			}
		} catch (IOException e) {
			System.out.println("An I/O error occurred: " + e.getMessage());
		} catch (SecurityException e) {
			System.out.println("No sufficient permission to create file: " + e.getMessage());
		}
	}
}

6 thoughts on “Java – How to create a new file | Code Factory”

  1. My wife and i ended up being now cheerful when Peter could finish up his investigation via the precious recommendations he gained when using the web page. It is now and again perplexing to simply possibly be giving out techniques that the others may have been making money from. And we also keep in mind we need the website owner to give thanks to for that. The entire explanations you made, the easy blog navigation, the relationships you can help to instill – it’s got all sensational, and it’s really aiding our son and us feel that the subject is interesting, which is certainly pretty mandatory. Many thanks for all!

    Liked by 1 person

  2. This is the precise weblog for anybody who needs to find out about this topic. You realize a lot its nearly exhausting to argue with you (not that I really would want…HaHa). You undoubtedly put a brand new spin on a topic thats been written about for years. Great stuff, just nice!

    Liked by 1 person

Leave a comment