2014-10-30 94 views
0

我正在嘗試讀取一個文件並打印出每行的子字符串。我無法弄清楚我的錯誤是什麼。我的鏈接有效,那麼導致錯誤的原因是什麼?java.io.FileNotFoundException,錯誤是什麼?

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

回答

1

FileNotFoundException異常==文件...沒有被發現。錯誤404.它只是不存在。

在這種情況下,您沒有指定文件,您指定了一個網頁 - 它不像這樣工作,您需要使用網絡相關類下載頁面,然後才能與之交互。

File類純粹用於硬盤上的文件(或連接的USB /磁盤/等)。

檢查出How to read a text from a web page with Java?幫助閱讀網頁。 (問題本身就是你要找的,答案是更高級的交互。)

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

Ë& OE

相關問題