Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stream has already been operated upon or closed, gained exception when trying to create Racers

I have the following 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());
}

which throws exception in this line :

.map(this::createRacer);

Methods to create racer that consists in the same class :

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('_'));
}

The Racer Class :

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 file :

DRR_Daniel Ricciardo_RED BULL RACING TAG HEUER
SVF_Sebastian Vettel_FERRARI
LHM_Lewis Hamilton_MERCEDES
KRF_Kimi Raikkonen_FERRARI ...

FileLoader class :

public Stream<String> createStreamFromFile(String file) throws IOException {

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

        return streamFromFile;
    }

}

I read about Stream Supplier but I can't figured It out so I will be grateful for any help how to fix my program.

like image 573
Maybe Programmer Avatar asked Mar 04 '23 00:03

Maybe Programmer


1 Answers

You are using a try-with-resources statement to create a stream. Thus, the stream will be closed when the method returns which defeats your purpose.

From the above resource (emphasis mine)

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.

A Stream extends BaseStream which extends AutoCloseable


Change your code to return the stream like

public Stream<String> createStreamFromFile(String file) throws IOException {
    return Files.lines(Paths.get(file));
}
like image 128
user7 Avatar answered Mar 05 '23 15:03

user7