如何将java.io.File转换或转换为java.io.List?

时间:2016-03-27 19:52:47

标签: java list file

这就是我到目前为止......

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获得的错误消息:     线程&#34; main&#34;中的例外情况java.lang.ClassCastException:java.io.File不能转发到最近点的java.util.List.ClosestPoints.main(ClosestPoints.java:185)

1 个答案:

答案 0 :(得分:2)

您无法将文件转换为列表,但您可以读取文件的内容并将其解析为列表。请考虑来自http://alvinalexander.com/blog/post/java/how-open-read-file-java-string-array-list的Alvin Alexander的示例代码:

/**
 *
 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;
  }
}