Java File createNewFile()

Java File [Java File] Java File


createNewFile() Java java.io.File

public boolean createNewFile() throws IOException

  • true
  • false

IOException I/O


createNewFile()


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

public class CreateFileExample {
    public static void main(String[] args) {
        // File
        File file = new File("example.txt");
       
        try {
            //
            boolean created = file.createNewFile();
           
            if (created) {
                System.out.println("");
            } else {
                System.out.println("");
            }
        } catch (IOException e) {
            System.out.println(": " + e.getMessage());
        }
    }
}

createNewFile()

  • example.txt

  • IOException

1

File file = new File("nonexistent_dir/example.txt");
try {
    file.createNewFile();  // IOException
} catch (IOException e) {
    e.printStackTrace();
}

File file = new File("nonexistent_dir/example.txt");
file.getParentFile().mkdirs();  //
try {
    file.createNewFile();
} catch (IOException e) {
    e.printStackTrace();
}

2

IOException


FileOutputStream

// FileOutputStream
try (FileOutputStream fos = new FileOutputStream("file1.txt")) {
    //
}

// createNewFile()
File file = new File("file2.txt");
file.createNewFile();  //

Files.createFile()

Java 7 NIO.2 API Files.createFile()

Path path = Paths.get("example.txt");
try {
    Files.createFile(path);  // FileAlreadyExistsException
} catch (IOException e) {
    e.printStackTrace();
}

Files.createFile()


  1. createNewFile()
  2. IOException
  3. try-with-resources
  4. Java 7+ Files.createFile()

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

public class AdvancedFileCreation {
    public static void main(String[] args) {
        String fileName = "data/output/log.txt";
        File logFile = new File(fileName);
       
        //
        File parentDir = logFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            boolean dirsCreated = parentDir.mkdirs();
            if (!dirsCreated) {
                System.err.println("");
                return;
            }
        }
       
        try {
            if (logFile.createNewFile()) {
                System.out.println(": " + logFile.getAbsolutePath());
            } else {
                System.out.println(": " + logFile.getAbsolutePath());
            }
        } catch (IOException e) {
            System.err.println(": " + e.getMessage());
        }
    }
}

createNewFile() Java Java NIO.2 API Files

Java File [Java File] Java File