Create folders programmatically along with permissions using java to save content to that location

16,926

Solution 1

In Java you can create files in any writeable directory on your system by doing something like:

File file1 = new File("/var/www/newDirectory/");
file1.mkdirs();

Then to create a file in that directory you can do something like this:

File file2 = new File(file1.getAbsolutePath() + "newFile.txt"); // You may need to add a "File.seperator()" after the "file1.getAbsolutePath()" if the trailing "/" isn't included
if (file2.exists() == false) {
    file2.createNewFile();
}

To ensure that your file is readable to the public you should add read permissions to the file:

file2.setReadable(true, false);

In Apache you can set up a virtual host that points to the directory where you would like to make files available from. By default on debian linux it is /var/www.

Solution 2

Don't use the File API. It is ridden with misbehavior for serious filesystem work.

For instance, if a directory creation fails, the .mkdir() method returns... A boolean! No exception is thrown.

Use Files instead.

For instance, to create a directory:

// Throws exception on failure
Files.createDirectory(Paths.get("/the/path"), 
      PosixFilePermissions.asFileAttribute(      
         PosixFilePermissions.fromString("rwxr-x---")
      ));

Solution 3

Use Java Files with PosixPermission. [Note- PosixPermission is not supported in Windows]

Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx");
Files.createDirectories(path, PosixFilePermissions.asFileAttribute(perms));
Share:
16,926
user850234
Author by

user850234

Updated on June 04, 2022

Comments

  • user850234
    user850234 about 2 years

    I have xampp installed in my windows system and lampp installed in my linux system. I want to create folder in the location "http://localhost/" using java. I have done the following :

    dirName = new File("http://localhost/"+name);
    if(!dirName.exists()) {
        dirName.mkdir();
    }
    

    Is it possible to do? The idea is to download some files to that location programatically. Download is working but how do I create folders so that I can access it via http://example.com/name. This is required to keep track of the user related content. I have access to the apache web server with lampp already installed. How can I create folders and save the downloads to that folder with programmatically assigning the permissions to the folder and contents within it so that saved contents can be download from there using wget method.

  • tresf
    tresf over 4 years
    The function Files.createDirectories will also handle subfolders, like mkdirs().
  • tresf
    tresf over 4 years
    The permissions are ignored if the umask is stronger than what's being set.