gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:46:27 26 4
gpt4 key购买 nike

这就是我到目前为止所拥有的......

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无法在closestpoints.ClosestPoints.main(ClosestPoints.java:185)处转换为java.util.List

最佳答案

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

关于java - 如何将 java.io.File 转换或转换为 java.io.List?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com