2013-04-29 41 views
1

我刚刚阅读了这个tutorial toRealPath(),如果路径引用的文件确实存在,应该返回绝对路径。toRealPath(),IO/NIO package Java

下面是来自同一教程的一个片段:

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/indeed.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) 
+0

显然该文件确实存在,并在正确的路径/位置 – Rollerball 2013-04-29 15:20:34

回答

1

根据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()); 
} 

您可以在这里http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/sun/nio/fs/UnixException.java#86

查看整个源根据实施,当NoSuchFileException被倒掉,一个ENOENT错误发生。 ENOENT on unix代表没有这样的文件或目录。

你确定文件“/home/user/Desktop/indeed.txt”存在吗?或者您有权访问它。

什么是命令ls -l /home/user/Desktop/indeed.txt

什么是你正在使用的JDK版本的结果呢?

+0

Java版本“1.7.0_21” Java(TM)SE运行环境(build 1.7.0_21-b11) – Rollerball 2013-04-29 16:20:35

+0

和-rw-rw-r-- 1个用户用户31 2013-04-25 16:52/home/user /Desktop/usnumbers.txt – Rollerball 2013-04-29 16:22:05

+0

对不起,我不知道为什么会发生这种情况。你运行java程序的用户是否是你的run ls命令的用户? – 2013-04-30 00:47:51

1

你能告诉我们抛出的确切异常吗?正如您提到的教程所说:

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

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

+0

我编辑与异常的printstacktrace问题。 – Rollerball 2013-04-29 15:19:21