【问题标题】:How to cast or convert java.io.File to java.io.List?如何将 java.io.File 转换或转换为 java.io.List?
【发布时间】:2016-03-27 19:52:47
【问题描述】:

这就是我目前所拥有的......

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 得到的错误消息: 线程“主”java.lang.ClassCastException 中的异常:java.io.File 无法在最接近点.ClosestPoints.main(ClosestPoints.java:185) 处强制转换为 java.util.List

【问题讨论】:

    标签: java list file


    【解决方案1】:

    您无法将文件转换为列表,但您可以读取文件的内容并将其解析为列表。考虑 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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 2021-12-27
      • 2013-07-21
      • 2014-05-12
      • 2013-06-03
      • 2018-08-11
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多