Reputation: 352
I'm trying to read a file to capture parameters to be passed to objects using Java 8 stream.
The file format is:
10 AA
15 BB
20 CC
Same number of objects have to be created as the number of lines, the objects take these parameters.
e.g Object a = new Object(10 , AA).
The file will always have a maximum of 3 lines.
I've come as far as reading the file, checking if it starts with a digit, splitting it at new line and placing each line in a List of String[ ].
List<String[]> input = new ArrayList<>();
try {
input = Files.lines(Paths.get("C:\\Users\\ubaid\\IntelliJ Workspace\\Bakery\\input.txt")).
filter(lines->Character.isDigit(lines.trim().charAt(0))).map(x-> x.split("\\r?\\n")).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
for(String a[] : input){
for(String s : a){
System.out.println(s);
}
}
Upvotes: 3
Views: 1042
Reputation: 44970
Assuming you have:
public class Type {
private int number;
private String text;
// constructor and other methods
}
And the file is well formatted:
List<Type> objs = Files.lines(path)
.map(s -> s.split(" "))
.map(arr -> new Type(Integer.parseInt(arr[0]), arr[1]))
.collect(Collectors.toList());
System.out.println(objs);
Upvotes: 4