How to create a file in a specified directory using Java



Problem Description

How to create a file in a specified directory?

Solution

This example demonstrates how to create a file in a specified directory using File.createTempFile() method of File class.

import java.io.File;

public class Main {
   public static void main(String[] args) throws Exception {
      File file = null;
      File dir = new File("C:/");
      file = File.createTempFile("JavaTemp", ".javatemp", dir);
      System.out.println(file.getPath());
   }
}

Result

The above code sample will produce the following result.

C:\JavaTemp37056.javatemp

The following is an example of file in a specified directory.

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 CreateFile {
   public static void main(String[] args) throws IOException {
      Path p1 = Paths.get("C:/");
      Files.createDirectories(p1.getParent());
      try {
         Files.createFile(p1);
      } catch (FileAlreadyExistsException e) {
         System.err.println("already exists: " + e.getMessage());
      }
   }
}

The above code sample will produce the following result.

BUILD SUCCESSFUL 
java_files.htm
Advertisements