简体   繁体   English

使用扫描仪读取Java中的文件

[英]Reading a file in Java with Scanner

I'm trying to get a program to read a text file but it's throwing a FileNotFoundException even though I have the potato.txt file set in the project directory. 我正在尝试获取一个程序来读取文本文件,但是即使我在项目目录中设置了potato.txt文件,它也会引发FileNotFoundException。

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

public static void main(String[] args) {
    String potato = "potato.txt"; // assume this line can't be changed at all

    Scanner scan = new Scanner(new File(potato)); // throws FileNotFoundException

    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        System.out.println(line);
    }


}

}

Try using the full Path, like this: 尝试使用完整路径,如下所示:

File file = new File("C:/temp/potato.txt"); //This is just an example path, look up your files path and put it here.
Scanner scan = new Scanner(file);

Also, don't forget to close your scanner when done (after your while -loop): 另外,别忘了在完成后关闭扫描仪(在while -loop之后):

scan.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM