【问题标题】:java.io.FileNotFoundException, what is the error?java.io.FileNotFoundException,错误是什么?
【发布时间】:2014-10-30 03:33:07
【问题描述】:

我正在尝试读取文件并打印出每一行的子字符串。我无法弄清楚我的错误是什么。我的链接有效,那么是什么导致了错误?

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();
			}
	}
}

【问题讨论】:

    标签: java java.util.scanner filereader filenotfoundexception


    【解决方案1】:

    FileNotFoundException == 文件...未找到。错误 404。它只是不存在。

    在这种情况下,您没有指定文件,而是指定了网页 - 它不是那样工作的,您需要使用网络相关的类来下载页面,然后才能与它进行交互。

    File 类纯粹用于硬盘驱动器(或连接的 USB/磁盘/等)上的文件。

    查看How to read a text from a web page with Java? 以获取阅读网页的帮助。 (问题本身有你要找的,答案是更高级的交互。)

    【讨论】:

      【解决方案2】:
      new File("https://www.cs.uoregon.edu/Classes/14F/cis212/assignments/phonebook.txt");
      

      问题是文件名。那不是文件名,它是 URL,它不是指文件,而是指 HTTP 资源。删除它,然后更改它:

      Scanner scan = new Scanner(file);
      

      到这里:

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

      电子与工程

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-11
        • 1970-01-01
        • 2018-12-21
        • 1970-01-01
        相关资源
        最近更新 更多