Julien Berthoud
Julien Berthoud

Reputation: 769

Change permission for all files inside a directory using JAVA

I'd like to write a piece of code in order to set all files inside a directory to writable (no read-only). My program is in JAVA and it should work both on Windows and Linux. So far my approach was to iterate over all the files contained in the directory and for each of them, set the permission to writable, using these methods:

  static void makeDosFileWritable(Path pathToFile) {
    try {
      Files.setAttribute(pathToFile.toAbsolutePath(), "dos:readonly", false);
       //logs
    } catch (IOException e) {
       //logs
    }
  }


  static void makeUnixFileWritable(Path pathToFile) {
    try {
      Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-rw-rw-");
      Files.setPosixFilePermissions(pathToFile, ownerWritable);
     //logs
    } catch (IOException e) {
     //logs
    }
  }

This works fine. The problem is, inside the top directory, I could also have nested directory. I was wondering how to handle this.

Upvotes: 0

Views: 2231

Answers (3)

Kevin Boone
Kevin Boone

Reputation: 4307

In Java, if you don't want to spawn an operating system utility to do it, you'll need to handle the directory recursion in your code. Implement a function that takes as its argument a File that represents a directory. Expand the files in the directory using, for example, File.listFiles(), then test each for whether it's a directory using File.isDirectory(). If it's a directory, call yourself recursively with the new directory.

There are lots of things to watch out for -- you don't want to expand the ".." directory explicitly if it appears in the list, for example. You might need to check for circular links. You might want to restrict the expansion to a particular depth, or a particular device, and so on.

It needs a fair amount of code to do this expansion in a helpful and robust way but, if you're well-organized, you'll only need to write it once.

Upvotes: 1

Paresh N
Paresh N

Reputation: 21

You can refer this Github repo - it has an implementation for changing permissions for Windows, *Nix and even MacOs. Relevant code can be found here.

The code may be older, however, the implementations should still work.

Upvotes: 2

Hung Vu
Hung Vu

Reputation: 643

This is what t I can think of. You can use CLI instead by calling Runtime.getRuntime().exec(//The command of your OS that allows user to change folder permission). This should be the simplest way.

Besides, if you are familiar with C or C++ and using Windows, you can take a look at JNA library to access native Windows function.

Upvotes: 0

Related Questions