gpt4 book ai didi

java - 读取文本文件并将内容添加到 ArrayList

转载 作者:行者123 更新时间:2023-12-01 17:47:42 25 4
gpt4 key购买 nike

我正在学习从文本文件获取输入并阅读内容的所有不同方法。我正在努力使用 try - catch block (带有资源)并读取文件名。

以下是我迄今为止为这部分编写的内容:-

public static void main(String[] args) 
{

ArrayList<StationRecord> data = new ArrayList<>();
String stationName = null;

Scanner scan = new Scanner(System.in);
System.out.println("What is the filename?");
String input = scan.nextLine();
File file = new File(input);

try(BufferedReader in = new BufferedReader(new FileReader(file))){

while(scan.hasNext()){

stationName = scan.nextLine();
int yearMonthDay = scan.nextInt();
int max = scan.nextInt();
int min = scan.nextInt();
int avg = scan.nextInt();
double dif = scan.nextDouble();

StationRecord sr = new StationRecord(yearMonthDay, max, min, avg, dif);
data.add(sr);
}

}
catch(IOException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();

}
}

我不仅尝试对一个文件执行此操作,而且还尝试对其中两个文件执行此操作。无论如何,这里是一个输入示例:-

控制台:文件名是什么?

TempData2018a.txt

输入此内容后,我尝试遍历文本文件中的数据并将其添加到 StationRecord 类型(我的其他类)的 ArrayList 中。

任何建议和指导将不胜感激!另外,任何有关如何使用 2 个文件执行此操作的输入都会很棒!

编辑:.txt 文件数据示例

PITTSBURGH ALLEGHENY CO AIRPORT PA
20180101 11 2 7 -22.614762
20180102 12 5 9 -20.514762
20180103 23 2 13 -16.414762

我试图将整个第一行存储在名为 stationName 的变量中。然后我尝试将下一个 int、int、int、int double 存储在 StationRecord 类型的 ArrayList 中。

最佳答案

既然已经是 2018 年了,请停止使用 new File(..) 并开始使用 nio API。由于您使用的是 Java 8,因此您可以轻松实现您想要实现的目标!因此,您可以像这样创建 StationRecord:

Path filePath = Paths.get(pathToFile);

String stationName = Files.lines(filePath)
.findFirst()
.get();

List<StationRecord> stationRecords =
Files.lines(filePath)
.skip(1) //Skip first line since it has station name
.map(line -> line.split("\\s")) // split at a space starting from 2nd line
.map(
stationData -> new StationRecord(Integer.valueOf(stationData[0]),
Integer.valueOf(stationData[1]), Integer.valueOf(stationData[2]),
Integer.valueOf(stationData[3]), Double.valueOf(stationData[4]))) // Create StationRecord object using the split fields
.collect(Collectors.toList()); // Collect result to an ArrayList

关于java - 读取文本文件并将内容添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53217833/

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