views:

1412

answers:

3

Hi all,

I'm looking for a code fragment, using which I must be to change the file permissions on unix. My project runs on java 1.4.2 ..

just a sample code example or methods which needs to be used will do..

Regards, Senny

+2  A: 

You're not the only one: http://stackoverflow.com/questions/459622/how-to-change-the-files-permission-and-last-modified-in-java

You could, in principle, use Runtime.exec("chmod ...") if the existing java.io.File methods aren't enough. But it wouldn't be portable.

David Zaslavsky
+1  A: 

You could also look at the Gnu ClassPath implementation of java.lang.File

They implemented the function based on JNI calls:

native/jni/java-io/java_io_VMFile.c:
  set_file_permissions: new helper function.
  Java_java_io_VMFile_setReadable: new native method to bakcup 1.6 methods
  in VMFile.java.

VMFile.java declares the call:

  /**
   * Set the write permission of the file.
   */
  public static synchronized native boolean setWritable(String path,
                                                        boolean writable,
                                                        boolean ownerOnly);

native/jni/java-io/java_io_VMFile.c does implement the desired function...

JNIEXPORT jboolean JNICALL
Java_java_io_VMFile_setWritable (JNIEnv *env,
                                 jclass clazz __attribute__ ((__unused__)),
                                 jstring name,
                                 jboolean writable,
                                 jboolean ownerOnly)
{
  return set_file_permissions (env, name, writable, ownerOnly,
                               CPFILE_FLAG_WRITE);
}

[...]
result = cpio_chmod (filename, permissions);

So... if you really want it, it is possible to implement it, by looking at the source of cpio.c: it calls chmod from libc standard library (LibGW32C does port some of those functions to Windows)

VonC
A: 

Just to be extra clear: Java 1.6 introduces getters/setters like File.canExecute() and File.setExecutable(boolean) for file permissions. So one solution is to use the latest JDK instead of the 1.4 you mentioned. Otherwise, as suggested, you can try to backport, or call out to platform-specific commands.

larham1

related questions