diegoaguilar
diegoaguilar

Reputation: 8376

Why isnt Java mkdirs working properly?

I wrote some code to create folders in a Java app running under Windows. It's not creating the folders but not going into exception though.

public static String createFolders(String client) {
    File folder = new File("/Users/Juan Manuel/Clientes/"+client);

    if (!folder.exists()) {

        try {
            folder.mkdirs();
            new File(folder.getPath()+"/IMSS").mkdir();
            new File(folder.getPath()+"/SAT").mkdir();
            new File(folder.getPath()+"/Finanzas").mkdir();
            new File(folder.getPath()+"/Otros").mkdir();
        }
        catch (Exception e) {
            return e.toString();
        }

    }
    return "";
}

I use the return value to check for any error but I get "" returned, so it's at least going through.

At Explorer's intended root path it's showing as C:\Users\Juan Manuel\Clientes.

Upvotes: 0

Views: 160

Answers (2)

wonhee
wonhee

Reputation: 1661

I didn't run your code in MS Window OS, but I'm not sure if c:\Users~ is equivalent to /Users~ in Java.

If you sure it's not go into your exception handling part, that means Java create file somewhere in your disk, not under C:\Users\Juan Manuel\Clientes though. Try to print what's absolute path of your "folder" file's path is and take a look if it's already exist or not.

So in catch statement. do e.printStackTrace(); first instead of returning error message if your program calling createFolders() doesn't print return strings. Checking e.toString() is sometimes not perfect to figure out root cause.

Also, try to use proper File create as Boris mentioned, I know that your calling would work ( since I was using it as well ), but using File( path, filename ); is more explicit and less error prone.

Lastly, check File class' JavaDoc http://docs.oracle.com/javase/7/docs/api/java/io/File.html#File(java.lang.String)

It will return NPE when given path is null, but it won't return exception for other cases.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

According to the documentation, you are going to see an exception only when SecurityException is thrown. If the code is unable to create a folder for any other reason, your code is not going to detect it, because it ignores the return code.

Change your method as follows to pay attention to the error:

try {
     if (!folder.mkdirs()) {
         return "root";
     }
     if (!(new File(folder.getPath()+"/IMSS").mkdir())) {
         return "IMSS";
     }
     if (!(new File(folder.getPath()+"/SAT").mkdir())) {
         return "SAT";
     }
     if (!(new File(folder.getPath()+"/Finanzas").mkdir())) {
         return "Finanzas";
     }
     if (!(new File(folder.getPath()+"/Otros").mkdir())) {
         return "Otros";
     }
} catch (...)

Upvotes: 1

Related Questions