now using Stream and try-with-resources syntax

This commit is contained in:
2020-06-11 12:48:08 -05:00
parent 50506d4465
commit 3c49635303

View File

@@ -12,6 +12,17 @@ class RandomNumberFileReader{
private ArrayList<Integer> numbers = new ArrayList<Integer>();
public RandomNumberFileReader(String file){
//reads text from file of integers, one on each line
//uses try-with-resources loop to automatically close BufferedReader
//uses Stream operations instead of while loop
try(BufferedReader reader = Files.newBufferedReader(Path.of(file));){
reader.lines().mapToInt(Integer::parseInt).forEach(num -> numbers.add(num));
}catch (IOException ex){
System.err.println(ex);
}
/*
//previous version retained for reference
//Reads in from a text file of integers, one on each line
try{
BufferedReader reader = Files.newBufferedReader(Path.of(file));
@@ -23,8 +34,9 @@ class RandomNumberFileReader{
} catch (IOException ex){
System.err.println(ex);
}
*/
}
public ArrayList<Integer> getNumbers(){
return numbers;
}