Question

I am currently working on a method that will create files and directories. Bellow is the use case & problem explained.

1) When a user specifies a path e.g "/parent/sub folder/file.txt", the system should be able to create the directory along with the file.txt. (This one works)

2) When a user specifies a path e.g "/parent/sub-folder/" or "/parent/sub-folder", the system should be able to create all directories. (Does not work), Instead of it creating the "/sub-folder/" or /sub-folder" as a folder, it will create a file named "sub-folder".

Here is the code I have

Path path = Paths.get(rootDir+"test/hello/");
    try {
        Files.createDirectories(path.getParent());
        if (!Files.isDirectory(path)) {
            Files.createFile(path);
        } else {
            Files.createDirectory(path);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
Was it helpful?

Solution

You need to use createDirectories(Path) instead of createDirectory(path). As explained in the tutorial:

To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method, createDirectories(Path, FileAttribute). As with the createDirectory(Path, FileAttribute) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:

Files.createDirectories(Paths.get("foo/bar/test"));

The directories are created, as needed, from the top down. In the foo/bar/test example, if the foo directory does not exist, it is created. Next, the bar directory is created, if needed, and, finally, the test directory is created.

It is possible for this method to fail after creating some, but not all, of the parent directories.

OTHER TIPS

Not sure of which File API you are using. But find below the simplest code to create file along with folders using java.io package.

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


public class FileTest {

    public static void main(String[] args) {
        FileTest fileTest = new FileTest();
        fileTest.createFile("C:"+File.separator+"folder"+File.separator+"file.txt");
    }

    public void createFile(String rootDir) {
        String filePath = rootDir;
        try {
            if(rootDir.contains(File.separator)){
                filePath = rootDir.substring(0, rootDir.lastIndexOf(File.separator));
            }
            File file = new File(filePath);
            if(!file.exists()) {
                System.out.println(file.mkdirs());
                file = new File(rootDir);
                System.out.println(file.createNewFile());
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top