简体   繁体   English

Java 8从输入文件流创建多个对象

[英]Java 8 Stream Multiple Object Creation from an input File

I'm trying to read a file to capture parameters to be passed to objects using Java 8 stream. 我正在尝试读取一个文件来捕获要使用Java 8流传递给对象的参数。

The file format is: 文件格式为:

10 AA 10 AA

15 BB 15 BB

20 CC 20 CC

Same number of objects have to be created as the number of lines, the objects take these parameters. 必须创建相同数量的对象作为行数,对象采用这些参数。

eg Object a = new Object(10 , AA). 例如,对象a =新对象(10,AA)。

The file will always have a maximum of 3 lines. 该文件最多总共有3行。

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[ ]. 我已经到了读取文件,检查它是否以数字开头,将其拆分为新行并将每行放在String of [List]中。

     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);

            }
        }

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM