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,但它没有这样做
我期待它打印文本文件。
由于您没有指定路径,程序将在当前目录中查找该文件。这可能与您放置文件的位置不同。为了避免不确定性,请使用此行:
scFile = new Scanner(new File("dog2.txt").toAbsoluteFile());
并在异常处理程序中放入:
System.out.println("File not found: " + ex.getMessage());
现在,它将打印查找文件的完整路径。
您可以在
File
构造函数中自行指定完整路径。
顺便说一句,您应该注意正确缩进源文件。按照你的方式,它很难阅读。