2016-03-27 44 views
0

這是我迄今爲止...如何將java.io.File轉換或轉換爲java.io.List?

List<Point> points = new ArrayList<Point>(); 
Scanner input = new Scanner(System.in); 
System.out.println("Enter the name of your file (fileName.dat):"); 
String fileName = input.nextLine(); 
points = (List<Point>)new File(fileName); 

我想投或轉換文件列表。 這是我從NetBeans獲得的錯誤消息: 線程「main」中的異常java.lang.ClassCastException:無法將java.io.File強制轉換爲最接近點處的java.util.List .ClosestPoints.main(ClosestPoints.java :185)

回答

2

您無法將文件轉換爲列表,但可以讀取文件的內容並將其解析爲列表。考慮來自Alvin Alexander的示例代碼http://alvinalexander.com/blog/post/java/how-open-read-file-java-string-array-list

/** 
* 
Open and read a file, and return the lines in the file as a list 
* of Strings. 
* (Demonstrates Java FileReader, BufferedReader, and Java5.) 
*/ 
private List<String> readFile(String filename) 
{ 
    List<String> records = new ArrayList<String>(); 
    try 
    { 
    BufferedReader reader = new BufferedReader(new FileReader(filename)); 
    String line; 
    while ((line = reader.readLine()) != null) 
    { 
     records.add(line); 
    } 
    reader.close(); 
    return records; 
    } 
    catch (Exception e) 
    { 
    System.err.format("Exception occurred trying to read '%s'.", filename); 
    e.printStackTrace(); 
    return null; 
    } 
} 
相關問題