java.lang.unsupportedoperationexception:'posix:permissions'在windows上不支持作为初始属性

z2acfund  于 2023-04-13  发布在  Java
关注(0)|答案(1)|浏览(939)

我使用的是Java7文件api。我写了一个类,在ubuntu上运行得很好,可以完美地创建目录,但当我在windows上运行相同的代码时,它会抛出错误:

Exception in thread "main" java.lang.UnsupportedOperationException: 'posix:permissions' not supported as initial attribute
    at sun.nio.fs.WindowsSecurityDescriptor.fromAttribute(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.createDirectory(Unknown Source)
    at java.nio.file.Files.createDirectory(Unknown Source)
    at java.nio.file.Files.createAndCheckIsDirectory(Unknown Source)
    at java.nio.file.Files.createDirectories(Unknown Source)
    at com.cloudspoke.folder_permission.Folder.createFolder(Folder.java:27)
    at com.cloudspoke.folder_permission.Main.main(Main.java:139)

我的文件夹类代码是

package com.cloudspoke.folder_permission;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipal;
import java.util.Set;

public class Folder{
    // attributes required for creating a Folder
    private UserPrincipal owner;
    private Path folder_name;
    private FileAttribute<Set<PosixFilePermission>> attr;

    public Folder(UserPrincipal owner,Path folder_name,FileAttribute<Set<PosixFilePermission>> attr){
        this.owner=owner;
        this.folder_name=folder_name;
        this.attr=attr;
    }
    //invoking this method will create folders
    public  void createFolder(){
        try {
            //createDirectories function is used for overwriting existing folder instead of createDirectory() method
            Files.createDirectories(folder_name, attr);
            Files.setOwner(folder_name, owner);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("created Folder "+this.folder_name);

    }
}

错误来自 createFolder 方法 Folder .
如何解决此错误?

ufj5ltwl

ufj5ltwl1#

你用 PosixFilePermission 只能与与posix兼容的操作系统一起使用:
一种文件属性视图,提供与实现可移植操作系统接口(posix)标准系列的操作系统所使用的文件系统上的文件通常相关联的文件属性的视图。
实现posix标准系列的操作系统通常使用具有文件所有者、组所有者和相关访问权限的文件系统。此文件属性视图提供对这些属性的读写访问windows unfortunatelly不支持posix文件系统,所以这就是代码无法工作的原因。要在windows中创建目录,应使用:new File("/path/to/folder").mkdir();这个/将自动更改为` 在Windows里。如果要一次创建整个路径,必须使用 mkdirs() 方法。更多信息:http://docs.oracle.com/javase/6/docs/api/java/io/file.html
要在windows中设置文件权限,必须使用 setReadable() , setWritable() 以及 setExecutable() . 是的 File 类方法并仅设置文件所有者的权限。注意,上述方法是在Java1.6中添加的。在旧版本中,您必须使用(windows版本): Runtime.getRuntime().exec("attrib -r myFile");

相关问题