【问题标题】:No such file or directory - Exception in thread "main" java.io.FileNotFoundException没有这样的文件或目录 - 线程“main”java.io.FileNotFoundException 中的异常
【发布时间】:2020-02-11 14:01:48
【问题描述】:

我正在做一个程序,它从我的 macbook 中的文本文件中读取数据,然后打印星号。问题是 Eclipse 甚至找不到文本文件。我多次检查文件目录是否正确。我只是不知道为什么会收到此错误。如果我能得到解决方案或建议,那将非常有帮助。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class FileIO 
{
    public static void main (String [] args) throws FileNotFoundException 
    {
        int num;
        Scanner reader = new Scanner (new File ("/User/3020418/Desktop/MyData.txt"));
        PrintWriter  writer = new PrintWriter (new File("/⁨Users/3020418⁩/⁨Desktop⁩/Output.txt"));  
        while (reader.hasNext())  
        {   // reads until EOF 
              num = reader.nextInt(); 
             System.out.print(num);
              if(num > 0)
              {
                  for (int i = 1; i < num; i++)
                  {
                      writer.print("x");
                  }
              }

              if(num == 0)
              {
                  writer.print(" ");
              }

              if(num < 0)
              {
                  for(int i = Math.abs(num); i > 0; i--)
                  {
                      writer.print("\n");
                  }
              }
        }
        writer.close();
        reader.close();


}

}

这是我不断收到的完整错误:

Exception in thread "main" java.io.FileNotFoundException: /User/3020418/Desktop/MyData.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at FileIO.main(FileIO.java:11)

【问题讨论】:

  • 下定决心。 /User/Users.

标签: java java-io filenotfoundexception file-not-found


【解决方案1】:

如果您使用的是 Mac,那么它应该是 /Users/3020418/Desktop/MyData.txt,您在 User 的末尾缺少一个 s... 可能吗?

【讨论】:

  • 真的吗?你已经检查过文件是否存在?你能读懂吗?而且您确实将第 11 行更改为看起来像 Scanner reader = new Scanner (new File ("/Users/3020418/Desktop/MyData.txt")); 是同样的错误吗?
  • 您尝试过@George Z 的解决方案吗?首先,这当然是更好的方法。
【解决方案2】:

不要使用绝对路径作为String 并弄乱文件分隔符,而是使用System.getProperty("user.home") 来获取主目录,然后使用File 类costructor 逐步构建路径/文件-附档:

File desktop = new File(System.getProperty("user.home"), "Desktop");
File myDataTxt = new File(desktop, "MyData.txt");

【讨论】:

    【解决方案3】:

    使用System.getProperty("user.home") 导航到主目录,然后找到您的文件。

    String home = System.getProperty("user.home");
    File f = new File(home + File.separator + "Desktop" + File.separator + "MyData.txt");
    

    为了独立于操作系统,请使用 File.separator 代替正斜杠或反斜杠。

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      相关资源
      最近更新 更多