【问题标题】:FileNotFoundException although the file is existFileNotFoundException 虽然文件存在
【发布时间】:2015-06-15 19:19:02
【问题描述】:

我正在尝试访问计算机中的某个文本文件,但我不断收到此异常,尽管路径正确且文件存在。 这是我的代码:

    public static void main(String[] args) throws IOException {

    File wordFile = new File("‪D:\\IDC\\Stuff\\wordList.txt");
    RandomAccessFile wordsList = new RandomAccessFile(wordFile, "rw");

    System.out.println(wordFile.exists());


}

错误:

Exception in thread "main" java.io.FileNotFoundException: ‪D:\IDC\Stuff\wordList.txt (The filename, directory name, or volume label syntax is incorrect)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:243)
at WordChecker.main(WordChecker.java:12)

【问题讨论】:

  • 你试过用System.out.println(wordFile.getAbsolutePath())打印wordFile的绝对路径吗?如果没有,请尝试在文件资源管理器中复制最后一条语句的输出,以检查路径是否存在。此外,您是否检查过您是否具有读取和写入所需文件的权限?
  • 我赌"wordList.txt.txt"是真实的文件名。 @Ohad121 你检查过你的文件名是你认为的吗?没有隐藏文件扩展名?
  • 你能在windows中打开文件吗?看起来更像是 Windows 错误,而不是文件未找到错误。
  • 我现在试试这个,但还是一样。我拥有该文件的权限,因为我创建了它并且我是计算机的管理员。我试图将文件移动到 eclips 的项目文件夹中,现在我只编写文件 nae 而没有像“wordList.txt”这样的整个路径,并且每次运行程序时它都会创建一个新文件,而不是从中读取。

标签: java file path filenotfoundexception randomaccessfile


【解决方案1】:

当我复制您的代码并尝试将其保存在 Eclipse 中时。我收到以下错误

我由此得出结论,虽然你的路径看起来是 'D:\\IDC\\Stuff\\wordList.txt' 但实际上并非如此。所以我做了什么,只需输入这一行 File file =new File("D:\\IDC\\Stuff\\wordList.txt"); 而不是从您的代码中复制它它起作用了。看来你也从某个地方复制了它,并且你遇到了编码问题。

还有一点,你应该使用 System.getProperty("file.separator") 而不是 \\ 或 / 就像下面一样

File wordFile = new File("‪D:" + System.getProperty("file.separator")
                + "IDC" + System.getProperty("file.separator") + "Stuff"
                + System.getProperty("file.separator") + "wordList.txt");

文件.分隔符

分隔文件路径组件的字符。这是 UNIX 上的“/”和 Windows 上的“\”。

【讨论】:

  • 天哪,这是正确的,在D:\(我认为是U+202A)之前有一个隐形字符。跨度>
【解决方案2】:

你能重命名文件吗?如果您从其他位置复制文件名并且其中包含不可见字符,这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2015-02-20
    • 1970-01-01
    • 2023-03-05
    • 2023-03-07
    相关资源
    最近更新 更多