toRealPath(),IO/NIO包Java

toRealPath(),IO/NIO包Java,java,exception,path,Java,Exception,Path,我刚刚读到,如果路径引用的文件确实存在,toRealPath()应该返回绝对路径 以下是同一教程中的一个片段: try { Path fp = path.toRealPath(); } catch (NoSuchFileException x) { System.err.format("%s: no such" + " file or directory%n", path); // Logic for case when file doesn't exi

我刚刚读到,如果路径引用的文件确实存在,toRealPath()应该返回绝对路径

以下是同一教程中的一个片段:

try {
       Path fp = path.toRealPath(); } catch (NoSuchFileException x) {
       System.err.format("%s: no such" + " file or directory%n", path);
       // Logic for case when file doesn't exist. } catch (IOException x) {
       System.err.format("%s%n", x);
       // Logic for sort of file error. }
因此,现在当我使用位于桌面上的现有文件时,例如(
Path inputPath=Paths.get(“/home/user/desktop/really.txt”
),它会给我一个异常,就像它不存在一样。 什么可能导致此问题? 真的非常感谢

编辑:我从中得到一个NoSuchFileException

java.nio.file.NoSuchFileException: /home/user/Desktop/indeed.txt
    at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
    at sun.nio.fs.UnixPath.toRealPath(UnixPath.java:833)
    at Pathss.main(Pathss.java:25)

您能告诉我们引发的确切异常吗?正如您提到的教程所述:

如果文件不存在或无法访问,此方法将引发异常


因此,您可能根本无法访问该文件。

根据jdk的来源,translateToIOException方法的实现如下:

private IOException translateToIOException(String file, String other) {
    // created with message rather than errno
    if (msg != null)
        return new IOException(msg);

    // handle specific cases
    if (errno() == UnixConstants.EACCES)
        return new AccessDeniedException(file, other, null);
    if (errno() == UnixConstants.ENOENT)
        return new NoSuchFileException(file, other, null);
    if (errno() == UnixConstants.EEXIST)
        return new FileAlreadyExistsException(file, other, null);

    // fallback to the more general exception
    return new FileSystemException(file, other, errorString());
}
您可以在这里查看整个源代码

根据实现,当抛出NoSuchFileException时,会发生eNONT错误。unix上的eNONT表示没有这样的文件或目录

您确定存在文件“/home/user/Desktop/decision.txt”吗?或者您有访问该文件的权限

ls-l/home/user/Desktop/execute.txt命令的结果是什么


您使用的jdk版本是什么?

我用异常的printstacktrace编辑了这个问题。显然,该文件确实存在,并且位于正确的路径/locationjava version“1.7.0_21”Java(TM)SE运行时环境(build 1.7.0_21-b11)和-rw-rw-r--1 user user 31 2013-04-25 16:52/home/user/Desktop/usnumbers.txt对不起,我不知道为什么会发生这种情况。您运行java程序的用户是您运行ls命令的用户吗?