Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 826
user850234 Avatar asked Jan 14 '13 19:01

user850234


3 Answers

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---")
      ));
like image 183
fge Avatar answered Nov 08 '22 09:11

fge


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

Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx");
Files.createDirectories(path, PosixFilePermissions.asFileAttribute(perms));
like image 22
Syed Mohamed Avatar answered Nov 08 '22 11:11

Syed Mohamed


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.

like image 2
travega Avatar answered Nov 08 '22 11:11

travega