How to create a file in a directory in java?

you will learn how to create a new file in java program and use of “file.separator” system property

  • 1-With Java 7, you can use Path, Paths, and Files:
package com.nourit.javaIO;

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 CreateFileIndirectory {

  public static void main(String[] args) throws IOException {
    Path path = Paths.get("/tmp/nourit/test.txt");
    try {

      Files.createDirectories(path.getParent());

      Files.createFile(path);
    } catch (FileAlreadyExistsException e) {
      System.err.println("already exists: " + e.getMessage());
    }

  }

}

  • 2- new File with absolute Filepath and File.separator
package com.nourit.javaIO;

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

public class CreateFileIndirectory1 {

  public static void main(String[] args) {
    String fileName = "newFile.txt";
    String workingDirectory = System.getProperty("user.dir");
    
    String absolutPath = workingDirectory + File.separator + fileName;
    
    System.out.println("absolutPath : " + absolutPath);
    
    File file = new File(absolutPath);

    try {
      if (file.createNewFile()) {
        System.out.println("File is created!");
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

Output

absolutPath : D:\Development\nourit-trunk\workspace_trunk\Java\newFile.txt
File is created!

 

  • 3- create a file in a specific directory that uses a variable in its name
package com.nourit.javaIO;

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

public class CreateFileIndirectory2 {

  public static void main(String[] args) {
    String fileName = "newFile.txt";
    String workingDirectory = System.getProperty("user.dir");
    
    File file = new File(workingDirectory, fileName);

    try {
      if (file.createNewFile()) {
        System.out.println("File is created!");
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
}

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Ein Gedanke zu „How to create a file in a directory in java?

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*