0

I know how to create directories inside any directory using Java. But I am unable to find a solution to add directories inside a directory which requires sudo permission to create a directory inside it.

For eg, I want to create new directories named abc/abc inside /var/log/.

I am uisng following code :

public class CreateDirectories{
    public static void main(String args[]){
    File file = new File("/var/log/java-jdbc/java-jdbc");
        if(!file.exists()){
            if (file.mkdirs()) {
                System.out.println("Directory is created!");
            } 
            else{
                System.out.println("Failed to create directory!");
            }
        }
    }
}

This code always runs giving output: Failed to create directory!

Prashant Prabhakar Singh
  • 1,120
  • 4
  • 15
  • 33
  • Your program will need to be run with sudo right. – litelite May 10 '17 at 12:42
  • You might want to take a look at `Runtime.exec()` to execute OS-commands in Java. – Andy May 10 '17 at 12:46
  • Possibile duplicate of [File.mkdir or mkdirs return false - Reason?](http://stackoverflow.com/questions/12202766/file-mkdir-or-mkdirs-return-false-reason) – Oneiros May 10 '17 at 12:53
  • 1
    The best you can do is `new ProcessBuilder("sudo", "mkdir", "/var/log/java-jdbc/java-jdbc")`. If sudo needs a password because it hasn’t already been authenticated, there is simply no way Java can do what you want, unless Java itself is run as root or as another user with permission to make that directory. – VGR May 10 '17 at 14:02
  • Thanks. So basically there is no way Java can access root directories(sudo needs permission)? I was begenning with logging in Java, I tried to keep logs in `/var/log/myLogs` the best place to keep log files. Where do we normally logs of a java application, if we can't access root directories from Java application – Prashant Prabhakar Singh May 10 '17 at 14:08

0 Answers0