为什么我的java代码在使用扫描仪文件时在VS代码中找不到文本文件,我是否把它放在错误的地方[重复]

问题描述 投票:0回答:1
Scanner scFile = null;
        try
        {
            scFile = new Scanner(new File("dog2.txt"));
        while(scFile.hasNext())
         {
           line = scFile.nextLine();

           Scanner scLine = new Scanner (line).useDelimiter("#");
           name = scLine.next();
           age = scLine.nextInt();
           pedigree = scLine.nextBoolean();
            
           Dog one = new Dog(name, age, pedigree);

           dogs[size] = one;
           size++;

            
         }
         scFile.close();

         for(int x = 0; x<dogs.length; x++)
         {
            System.out.println(dogs[x]);
         }
        }catch(FileNotFoundException ex)
        {
            System.out.println("File not found");
        }

它返回找不到文件 这是代码,它读取文本文件dog2.txt,但它没有这样做

我期待它打印文本文件。

java class object
1个回答
0
投票

由于您没有指定路径,程序将在当前目录中查找该文件。这可能与您放置文件的位置不同。为了避免不确定性,请使用此行:

scFile = new Scanner(new File("dog2.txt").toAbsoluteFile());

并在异常处理程序中放入:

System.out.println("File not found: " + ex.getMessage());

现在,它将打印查找文件的完整路径。

您可以在

File
构造函数中自行指定完整路径。

顺便说一句,您应该注意正确缩进源文件。按照你的方式,它很难阅读。

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