如何获取字符串参数(将是文件的路径名)并执行文件方法,如exists()和setReadOnly?

时间:2015-02-21 20:04:00

标签: java string file-io

    import java.nio.file.Files;
    import java.nio.file.FileSystems; 
    import java.nio.file.Paths;
    import java.nio.file.Path;
    public class Attrib {
/* Command::
attrib name       where name must be the name of a file and its path.
Action:
Makes the file read only.

 */
public Attrib(String name){
   final Path path = Paths.get(name);
   Files.setAttribute(path, "dos:readonly", true); 
   throws NoSuchFileException;



}

private void f(String name){
    System.out.print(name);
}

} 此程序的目的是使现有文件只读。 出于某种原因,当我尝试编译“找不到符号 - 方法exists()”时,我不断收到错误代码。我猜你不能在表示为字符串的路径名上执行exists()或任何其他File方法?也许我可以将字符串路径名转换为文件对象或其他东西?

1 个答案:

答案 0 :(得分:0)

使用java.nio.file,它对文件属性有更好的支持。

假设您在Windows上运行,例如,此代码将起作用:

final Path path = Paths.get(thename);

Files.setAttribute(path, "dos:readonly", true);

您可以捕获Files.setAttribute()抛出的异常,例如,如果文件不存在,则抛出NoSuchFileException等。

上述代码的等价物可以是:

final Path path = Paths.get(thename);

final DosFileAttributeView view 
    = Files.getFileAttributeView(path, DosFileAttributeView.class);

view.setReadOnly(true);

事实上,如果您希望更改多个参数,建议您浏览FileAttributeView

但请注意,此代码当然是“非便携式”#34;从某种意义上说它只适用于支持FileSystem文件属性的dos。例如,在Unix系统上,您可能希望改变POSIX权限。