简体   繁体   中英

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.

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):

scan.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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