1

このチュートリアルを読んだところ、パスが参照するファイルが実際に存在する場合、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/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)
4

2 に答える 2

2

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 エラーが発生しました。Unix の ENOENT は No such file or directory を表します。

ファイル「/home/user/Desktop/indeed.txt」が存在しますか? または、アクセスする権限を持っています。

コマンド ls -l /home/user/Desktop/indeed.txt の結果は何ですか

使用しているjdkのバージョンは何ですか?

于 2013-04-29T15:52:19.733 に答える
1

スローされた正確な例外を教えていただけますか? あなたが言及したチュートリアルとして:

ファイルが存在しないかアクセスできない場合、このメソッドは例外をスローします。

したがって、単にそのファイルにアクセスできない可能性があります。

于 2013-04-29T15:13:11.863 に答える