How to Create a File in Java
This tutorial shows you how to create a file using java. First we explore the old way using the File
class. Next we explore the new Path
class introduced in Java 7.
Create a File pre java 7 way
mkdirs()
creates a new, empty directory if a directory with this name does not exist yet.file.createNewFile()
creates a new, empty file if a file with this name does not exist yet.
package com.memorynotfound.file;
import java.io.File;
import java.io.IOException;
public class CreateFileUsingFile {
public static void main(String... args){
try {
File file = new File("/tmp/foo/bar.txt");
if (file.getParentFile().mkdirs()){
System.out.println("directories created");
} else {
System.out.println("directories already exist");
}
if (file.createNewFile()){
System.out.println("file created");
} else {
System.out.println("file already exitst");
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
Create a File from java 7 and beyond
Files.createDirectories()
creates a new, empty directory if a directory with this name does not exist yet. This method does not throw an exception when the directories already exist.files.createFile()
creates a new, empty file if a file with this name does not exist yet. This method throws aFileAlreadyExistsException
if the file already exists.
package com.memorynotfound.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;
public class CreateFileUsingPath {
public static void main(String... args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}