Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.mkdir() and mkdirs() are creating file instead of directory

I use the following code:

final File newFile = new File("/mnt/sdcard/test/");
newFile.mkdir(); // if I use mkdirs() result is the same

And it creates an empty file! Why?

like image 502
artem Avatar asked Dec 19 '12 13:12

artem


People also ask

Why does mkdir not create directory?

mkdir: cannot create directory – Permission denied The reason for this error is that the user you're running the mkdir as, doesn't have permissions to create new directory in the location you specified. You should use ls command on the higher level directory to confirm permissions.

What is the difference between mkdir and mkdirs?

mkdirs() will create the specified directory path in its entirety where mkdir() will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create. In other words mkdir() is like mkdir and mkdirs() is like mkdir -p . new File("/tmp/one/two/three").

How to create a file and directory in Java?

In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false​.

How to put file in directory Java?

Use: File file = new File("Z:\\results\\results. txt"); You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.


2 Answers

You wouldn't use mkdirs() unless you wanted each of those folders in the structure to be created. Try not adding the extra slash on the end of your string and see if that works.

For example

final File newFile = new File("/mnt/sdcard/test");
newFile.mkdir();
like image 101
colin-higgins Avatar answered Oct 23 '22 01:10

colin-higgins


When I need to ensure that all dirs for a file exist, but I have only filepath - i do

   new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();
like image 26
Der Zinger Avatar answered Oct 23 '22 01:10

Der Zinger