gpt4 book ai didi

java - 流已被操作或关闭,尝试创建赛车手时获得异常

转载 作者:行者123 更新时间:2023-12-04 17:42:45 24 4
gpt4 key购买 nike

我有以下类(class):

public List<Racer> createListOfRacers() throws IOException {
Stream<String> abbreviationsOfRacers = fileLoader.createStreamFromFile("src/main/resources/abbreviations.txt");

Stream<Racer> racerList = abbreviationsOfRacers
.map(this::createRacer);

return racerList.collect(toList());
}

在这一行抛出异常:
.map(this::createRacer);

创建包含在同一类中的 Racer 的方法:
private Racer createRacer(String line) {
return new Racer(extractAbbreviationOfTheRacer(line), extractNameOfTheRacer(line), extractTeamOfTheRacer(line));
}

private String extractNameOfTheRacer(String line) {
return line.substring(line.indexOf('_') + 1, line.lastIndexOf('_'));
}

private String extractTeamOfTheRacer(String line) {
return line.substring(line.lastIndexOf('_') + 1);
}

private String extractAbbreviationOfTheRacer(String line) {
return line.substring(0, line.indexOf('_'));
}

赛车类:
public class Racer {

private String abbrevition;
private String name;
private String team;
private String result;


public Racer(String abbrevition, String name, String team) {
this.abbrevition = abbrevition;
this.name = name;
this.team = team;
}

public Racer() {
}

Abbreviations.txt 文件:
DRR_Daniel Ricciardo_RED BULL RACING TAG HEUER
SVF_Sebastian Vettel_FERRARI
LHM_Lewis Hamilton_MERCEDES
KRF_Kimi Raikkonen_FERRARI ...

文件加载器类:
public Stream<String> createStreamFromFile(String file) throws IOException {

try (Stream<String> streamFromFile = Files.lines(Paths.get(file))) {

return streamFromFile;
}

}

我阅读了有关 Stream 供应商的信息,但我无法弄清楚,因此如果您能帮助我修复我的程序,我将不胜感激。

最佳答案

您正在使用 try-with-resources创建流的语句。因此,当该方法返回时,流将被关闭,这违背了您的目的。

来自上述资源( 重点矿 )

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.



一个 Stream扩展 BaseStream扩展 AutoCloseable
更改您的代码以返回流
public Stream<String> createStreamFromFile(String file) throws IOException {
return Files.lines(Paths.get(file));
}

关于java - 流已被操作或关闭,尝试创建赛车手时获得异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59442028/

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