How to change file permissions from Java 1.4.2?

2019-06-21 07:05发布

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

3条回答
虎瘦雄心在
2楼-- · 2019-06-21 07:27

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.

查看更多
Ridiculous、
3楼-- · 2019-06-21 07:44

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)

查看更多
迷人小祖宗
4楼-- · 2019-06-21 07:51

You're not the only one: How to change the file's 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.

查看更多
登录 后发表回答