mkdir() is not creating the new directory

喜你入骨 提交于 2019-11-29 09:16:00
RNJ

You have to use mkdirs() with an s if you want to create multiple directories. It is probably also worth checking that you canWrite() to the location as some places are permissioned. Both of these are on the File class

its obj.mkdirs()

have a look to this:

File  f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());

The first print won't create a directory and returns false but the second does and returns true

Create directory example

it looks like you'll need to work on your path a bit as it doesn't look like File will infer "abc."

Also, make sure you have permissions on the path you're attempting to create the directory. If you don't, it will fail. It has been a while since I've played with Java, so not sure if you'd need to do mkdir calls the entire way down the path (ie /here/, /here/now-here/, /here/now-here/final) or not. Think it may be recursive but that'd be worth verifying.

Actually, from looking at the other answers looks like mkdirs would be recursive, mkdir is not. I'd go with mkdirs especially if the input isn't going to be known from the onset otherwise you'll end up writing a function with mkdir that does the exact same thing.

In your case you can make use of makedirectories method in File class.

File dir = new File("path name");
boolean isCreated = dir.mkdirs();

Here makedirectories method will create all directories that are missing in the path which the file object represent.

Source and reference is below (explained in detail).

http://www.flowerbrackets.com/create-directory-java-program/

https://docs.oracle.com/javase/6/docs/api/java/io/File.html#canWrite%28%29

cristi

mkdir needs the abstract path, not the relative path. try to use...

File f2 = new File (f1, "C:\\");

... for example.

From Java DOC:

public boolean mkdir()

Creates the directory named by this abstract pathname.

Returns:

true if and only if the directory was created; false otherwise

Throws:

SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method does not permit the named directory to be created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!