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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With