Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何获取字符串参数(将是文件的路径名)并对其执行exists()和setReadOnly等文件方法?_Java_String_File Io - Fatal编程技术网

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

Java 如何获取字符串参数(将是文件的路径名)并对其执行exists()和setReadOnly等文件方法?,java,string,file-io,Java,String,File Io,} 此程序的目的是使现有文件只读。 由于某种原因,当我试图编译“找不到符号-方法exists()”时,我不断得到错误代码。我猜您不能对表示为字符串的路径名执行exists()或任何其他文件方法?也许我可以将字符串路径名转换为文件对象或其他什么 使用java.nio.file,它对文件属性有更好的支持 例如,假设您在Windows上运行,此代码将正常工作: import java.nio.file.Files; import java.nio.file.FileSystems;

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

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

例如,假设您在Windows上运行,此代码将正常工作:

    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);
}
您可以捕获
Files.setAttribute()
引发的异常,例如,如果文件不存在,它可以引发
NoSuchFileException

上述代码的等效代码可以是:

final Path path = Paths.get(thename);

Files.setAttribute(path, "dos:readonly", true);
事实上,如果您希望更改多个参数,建议通过
FileAttributeView


但是请注意,此代码当然是“不可移植的”,因为它只适用于支持
dos
文件属性的
文件系统。例如,在Unix系统上,您可能需要更改POSIX权限。

嘿,谢谢您的回复。我一直在乱搞我的代码,试图让它工作。我导入了java.nio.file.Files、文件系统和路径,现在我在这里得到一个错误:final Path Path=Path.get(name);它说“找不到符号变量路径”。知道哪里出了问题吗?我更新的代码在上面,你不使用Java 7+?这不是我要问的。请注意,您似乎没有导入java.nio.file.path,这也是您需要的。另外,我不使用BlueJ,所以我无法帮助您使用这个IDE。我不确定您所说的Java7+是什么意思。导入路径之后,关于我的throws子句出现了一个错误代码,但是我现在没有时间去弄清楚应该在哪里声明它,因为我现在必须去工作。今晚晚些时候我会做一些研究。我没有足够的支持率来支持你,但我只是想给你一个加号。再次感谢@fge
final Path path = Paths.get(thename);

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

view.setReadOnly(true);