Java 8 从输入文件创建流式多对象
Java 8 Stream Multiple Object Creation from an input File
我正在尝试读取文件以捕获要使用 Java 8 流传递给对象的参数。
文件格式为:
10AA
15 BB
20 CC
必须创建与行数相同数量的对象,对象采用这些参数。
例如 Object a = new Object(10 , AA).
文件总是最多 3 行。
我已经阅读了文件,检查文件是否以数字开头,将其拆分为新行并将每一行放入字符串列表[]。
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);
}
}
假设你有:
public class Type {
private int number;
private String text;
// constructor and other methods
}
文件格式正确:
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);
我正在尝试读取文件以捕获要使用 Java 8 流传递给对象的参数。
文件格式为:
10AA
15 BB
20 CC
必须创建与行数相同数量的对象,对象采用这些参数。
例如 Object a = new Object(10 , AA).
文件总是最多 3 行。
我已经阅读了文件,检查文件是否以数字开头,将其拆分为新行并将每一行放入字符串列表[]。
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);
}
}
假设你有:
public class Type {
private int number;
private String text;
// constructor and other methods
}
文件格式正确:
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);