有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的程序找不到我要扫描的文本文件?

我试着把文件放在尽可能多的地方,看看它们是否有用。我也试着使用直接路径,但也没用。我有一台mac电脑,不知道这是不是把事情搞砸了

public static void main(String[] args) throws FileNotFoundException{
    String nextString=null;
    PopularName nextName;
    String[] info=new String[5];
    Scanner infile = new Scanner(new File("LastNames.txt"));    


共 (2) 个答案

  1. # 1 楼答案

    代码中还有更多错误:

    1. Scanner将其作为参数文件(FileReader在这里没有意义)
    2. 您不关心例外情况->;要么尝试catch block,要么您的方法必须将其抛出到更高级别——请参见下面的工作示例

    文件的路径应该相对于绝对值项目的根

    public class Main {
        public static void main(String[] args) throws FileNotFoundException {
            Scanner inFile = new Scanner(new File("file.txt"));
            while (inFile.hasNext()) {
                System.out.println(inFile.next());
            }
        }
    }
    
  2. # 2 楼答案

    如果你使用

    System.getProperty("user.dir");
    

    您可以获取项目的当前根目录。 因此,如果你把一个文件放在那里,你可以阅读如下:

    new FileReader(System.getProperty("user.dir") + "/LastNames.txt");