177

If I want to create a file in C:/a/b/test.txt, can I do something like:

File f = new File("C:/a/b/test.txt");

Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.

MattGotJava
  • 185
  • 3
  • 14
Uerefer
  • 1,803
  • 2
  • 12
  • 4

13 Answers13

273

The best way to do it is:

String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);

f.getParentFile().mkdirs(); 
f.createNewFile();
RMT
  • 7,040
  • 4
  • 25
  • 37
53

You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().

File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
48

NIO.2

With NIO.2 in Java 7, you can use Path, Paths, and Files:

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 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());
        }
    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
14

Use:

File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();

Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.

Marcelo
  • 11,218
  • 1
  • 37
  • 51
4
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
    File f = new File(path);
    File f1 = new File(fname);

    f.mkdirs() ;
    try {
        f1.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

This should create a new file inside a directory

Mayank
  • 13
  • 4
Chitta
  • 47
  • 2
2

A better and simpler way to do that :

File f = new File("C:/a/b/test.txt");
if(!f.exists()){
   f.createNewFile();
}

Source

Mehdi
  • 1,340
  • 15
  • 23
2

Surprisingly, many of the answers don't give complete working code. Here it is:

public static void createFile(String fullPath) throws IOException {
    File file = new File(fullPath);
    file.getParentFile().mkdirs();
    file.createNewFile();
}

public static void main(String [] args) throws Exception {
    String path = "C:/donkey/bray.txt";
    createFile(path);
}
MasterJoe
  • 2,103
  • 5
  • 32
  • 58
1

Create New File in Specified Path

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

public class CreateNewFile {

    public static void main(String[] args) {
        try {
            File file = new File("d:/sampleFile.txt");
            if(file.createNewFile())
                System.out.println("File creation successfull");
            else
                System.out.println("Error while creating File, file already exists in specified path");
        }
        catch(IOException io) {
            io.printStackTrace();
        }
    }

}

Program Output:

File creation successfull

AKHY
  • 291
  • 2
  • 3
1

To create a file and write some string there:

BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write("");         // for empty file
bufferedWriter.close();

This works for Mac and PC.

Kirill Ch
  • 5,496
  • 4
  • 44
  • 65
0

For using the FileOutputStream try this :

public class Main01{
    public static void main(String[] args) throws FileNotFoundException{
        FileOutputStream f = new FileOutputStream("file.txt");
        PrintStream p = new PrintStream(f);
        p.println("George.........");
        p.println("Alain..........");
        p.println("Gerard.........");
        p.close();
        f.close();
    }
}
0

When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.

    String absolutePath = ...
    try{
       File file = new File(absolutePath);
       file.mkdirs() ;
       //all parent folders are created
       //now the file will be created when you start writing to it via FileOutputStream.
      }catch (Exception e){
        System.out.println("Error : "+ e.getmessage());
       }
Tom
  • 1
  • 1
0

I was here tackling this same problem and I finally solved it.

The goal is to create a file (example a .txt file) within a folder.

Things you'll need:

  1. Folder name

Instead of this:

File f = new File("C:/a/b/test.txt");

Try

//get the file's absolute path. You could input it yourself
// but I think it is better to have a function to handle
// system rules on how to format the path string

String myFolder = "b";
String myFile = "test.txt";
String folderPath = myFolder.getAbsolutePath(); //will get the entire path for you

String pathToFile = folderPath + File.separator + myFile;

// this will probably throw a exception, you want to make sure you handle it
try {
    File newFile = new File(pathToFile);
    if (newFile.createNewFile()) {    
         System.out.println("bwahahah success");
    }
    else {
        System.out.println("file creation failed");
    }
}catch(IOException e) {
    System.out.println(e.getMessage());   // you will need to print the message in order to get some insight on what the problem is.
}

// you can also add a throw if within the if statement with other checks in order to know where the error is coming from, but to keep it short this is the gist of it.

// Really hope this will assist anyone that stumbles upon this same issue.

Other resources for further reading: everything on java paths & files

Please comment if there is anything I might also overlook, lemme absorb some of that knowledge

0

Just joining some answers together.

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

class Scratch {
    public static void main(String[] args) {

        String fileTargetLocation = "C:\\testing\\";
        String fileNameAndExtension = "test.txt";

        boolean fileCreated = createFile(fileTargetLocation, fileNameAndExtension);
        if (fileCreated) {
            String stringForFile = "This is some test text to write into the file.";
            writeIntoFile(fileTargetLocation, fileNameAndExtension, stringForFile);
        }
    }

    /**
     * Attempts to create a file at the given location, with the given file name and desired extension.
     *
     * @param fullPath             full path to folder in which the file needs to be created, example: C:\testing\
     *                             (ending with a foreword slash)
     * @param fileNameAndExtension file name and desired extension. Example: environment.properties, test.txt
     * @return successful file creation boolean
     */
    public static boolean createFile(String fullPath, String fileNameAndExtension) {
        try {
            return new File(fullPath + fileNameAndExtension).createNewFile();
        } catch (IOException io) {
            io.printStackTrace();
        }
        return false;
    }

    /**
     * Attempt to write into the given file.
     *
     * @param fullPath             full path to folder in which the file needs to be created, example: C:\testing\
     *                             (ending with a foreword slash)
     * @param fileNameAndExtension file name and extension. Example: environment.properties, test.txt
     * @param whatToWriteToFile    string to write to the file
     */
    public static void writeIntoFile(String fullPath, String fileNameAndExtension, String whatToWriteToFile) {
        try (BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(fullPath + fileNameAndExtension))) {
            bufferedWriter.write(whatToWriteToFile);
        } catch (IOException io) {
            io.printStackTrace();
        }
    }
}
BernardV
  • 640
  • 10
  • 28