0

I have mkdirs code like that;

File dir = new File ("/Mydir/");
            if(dir.exists()==false) {
                dir.mkdirs();
            }

it is normal working and create directory on windows but not working on linux..

Ozan
  • 1,191
  • 2
  • 16
  • 31
  • 4
    Permissions probably. – Alexander O'Mara Dec 17 '15 at 20:11
  • 1
    It's probably trying to create the directory in a different location on Linux, since `/Mydir/` refers to an absolute path, rather than a relative path like on Windows. (i.e. `/Mydir/` vs `C:\path\to\current\directory\Mydir\ `) – resueman Dec 17 '15 at 20:11
  • @resueman so how can I create a folder on common path (for all users in linux computers ie.) – Ozan Dec 17 '15 at 20:15
  • @Ozi I believe `./Mydir/` would use a relative path (since `.` refers to the current directory). Or you could simply leave off the initial `/` – resueman Dec 17 '15 at 20:16
  • 2
    also it is always better to use the File.seperator() as in new File("src" + File.separator + "trials"); to avoid OS dependency instead of backslash or forward slash. – Prabhakaran Dec 17 '15 at 20:19
  • this is how relative path in java http://stackoverflow.com/questions/1131500/using-relative-directory-path-in-java – Prabhakaran Dec 17 '15 at 20:23
  • @resueman I see a different behavior in Windows from what you mentioned. The folder is created at the root level of my current drive which is "C". So the directory path is "C:\Mydir" – vinay Dec 17 '15 at 20:23
  • 3
    Better than using a 20-year-old method that returns no information about why it failed, is to use [Files.createDirectories](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#createDirectories-java.nio.file.Path-java.nio.file.attribute.FileAttribute...-)(dir.toPath()), which is guaranteed to either succeed or throw an exception containing a useful explanation of why it failed. – VGR Dec 17 '15 at 20:30

1 Answers1

0

/MyDir/ is a reference to a directory inside root-dir / - you'll need root privileges to write there.

For creating a directory inside user home you could use "~/MyDir" in linux - but that will not work again in Windows.

If you're forced to use old-style File operations you could go

 new File(new File(System.getProperty("user.home")), "MyDir").mkdir();

Better yet would be to invoke

 Files.createDirectories(
    Paths.get(System.getProperty("user.home"), "MyDir"));
Jan
  • 13,738
  • 3
  • 30
  • 55