没有这样的文件或目录-线程“ main”中的异常java.io.FileNotFoundException

问题描述 投票:0回答:3

我正在做一个程序,该程序从我的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)
java java-io filenotfoundexception file-not-found
3个回答
0
投票

不是使用绝对路径作为String并弄乱了文件分隔符,而是使用System.getProperty("user.home")以获得主目录,然后使用File类构造函数逐步构建路径/通过文件-文件:

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

0
投票

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

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

为了独立于操作系统,请使用前斜杠或后斜杠的File.separator intead。


0
投票

[如果您使用的是Mac,则应为/Users/3020418/Desktop/MyData.txt,可能是s末尾缺少了User ...也许?

© www.soinside.com 2019 - 2024. All rights reserved.