user2071377
user2071377

Reputation:

How to create a new directory using java?

I am using the following code to create folder but it does not create it (output is failed) and does not throw any exception.

Folder java is already created, I need to pass the folder name and create it in the java folder.

private String CreateFolder(String myfolder) {
        try {
            String dir = "../Java/" + myfolder;
            boolean result = false;
            File directory = new File(dir);

            if (!directory.exists()) {
                result = directory.mkdir();

                if (result) {
                    System.out.println("Folder is created");
                    return dir;
                } else {
                    return "failed";
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        return "";
    }

Upvotes: 0

Views: 11499

Answers (5)

lbear
lbear

Reputation: 820

Please make sure the folder ../Java/ exits. If there is no folder Java. The code won't work. If you really want create folder Java automaticlly. Please use direcotry.mkdirs() instead.

Upvotes: 0

Yakiv Mospan
Yakiv Mospan

Reputation: 8224

Try something like this :

  public static void main(String[] args)
{
    String path = "E:\\test";
    createFolder(path);
}

private static boolean createFolder(String theFilePath)
{
    boolean result = false;

    File directory = new File(theFilePath);

    if (directory.exists()) {
        System.out.println("Folder already exists");
    } else {
        result = directory.mkdirs();
    }

    return result;
}

Make sure to use correct root dir path (for example if you want to create folder inside of "../somefolder" it must be created already) if you want to use mkdir().

Note you need to set two slashes after Drive name. Like this "E:\\".

You can find more info here.

Upvotes: 6

Sunil Kpmbl
Sunil Kpmbl

Reputation: 811

Is this part of a web application? then use context path instead of abs path. Also use File.separator instead of slashes(/)

Upvotes: -1

bluearrow
bluearrow

Reputation: 904

You can try File.mkdirs() to try make nest directories and print the directory absolute path. I think you use the wrong path of "Java".

System.out.println(directory.getAbsolutePath())

Upvotes: 0

user2041815
user2041815

Reputation: 26

Please try giving absolute path to the directory instead of relative path.

Upvotes: 1

Related Questions