简体   繁体   中英

java.io.FileNotFoundException, what is the error?

I'm trying to read a file and print out a substring of each line. I cant figure out what my error is. My link works, so what is causing the error?

 import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class FileReader { public void fileReader() { File file = newFile("https://www.cs.uoregon.edu/Classes/14F/cis212/assignments/phonebook.txt"); try{ Scanner scan = new Scanner(file); while(scan.hasNextLine()) { String numAndName = scan.nextLine(); String newNum = numAndName.substring(0, 8); System.out.println(newNum); } scan.close(); } catch(FileNotFoundException e) { e.printStackTrace(); } } } 

FileNotFoundException == The file... wasn't found. Error 404. It's just not there.

In this case, you didn't specify a file, you specified a webpage - it doesn't work like that, you need to use network-related classes to download the page before you can interact with it.

the File class is purely for files on your harddrive (or connected USBs / disks / etc).

Check out How to read a text from a web page with Java? for help reading webpages. (The question itself has what you're looking for, the answers are more advanced interaction.)

new File("https://www.cs.uoregon.edu/Classes/14F/cis212/assignments/phonebook.txt");

The problem is the filename. That isn't a filename, it's a URL, and it doesn't refer to a file, it refers to an HTTP resource. Remove it, and change this:

Scanner scan = new Scanner(file);

to this:

Scanner scan = new Scanner(new URL("https://www.cs.uoregon.edu/Classes/14F/cis212/assignments/phonebook.txt").openStream());

E&OE

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