java 从文件中解析数组

wbrvyc0a  于 2023-05-12  发布在  Java
关注(0)|答案(1)|浏览(103)

从文件中阅读数组时遇到问题。这在溪流中怎么能做到?我需要计算整个字符串并将其放入Student字段
// # Name Surname Marks
// 1 Mike Scott [4,5,5]
// 2乔·琼斯[1,2,3]

class Student6 {

int ID;
String Name;
String Surname;
Integer[] marks;

public Student6(int ID, String name, String surname, Integer[] marks) {
    this.ID = ID;
    Name = name;
    Surname = surname;
    this.marks = marks;
}

public static void main(String[] args) {
    String path1 = "C:\\Users\\Professional\\IdeaProjects\\Lesson\\src\\StreamAPI\\FileStream";
    List<String> stream1 = Files.lines(Paths.get(path1)).toList();
    String[] arr = new String[stream1.size()];
    for (int i = 0; i < stream1.size(); i++) {
        arr[i] = stream1.get(i);
    }

    List<Student6> student4s = Stream.of(arr)
            .filter(line -> !line.startsWith("#"))
            .map(l -> {
                String s = l.split(" ")[3];
                String[] chars = s.split("");
                Integer[] integers = new Integer[3];

                for (int i = 0; i < chars.length; i++) {
                    if (chars[i].matches("[0-9]")) {
                        int c = 0;
                        integers[c++] = Integer.parseInt(chars[i]);
                    }
                }
                out.println(Arrays.toString(integers));
                return new Student6(Integer.parseInt(l.split(" ")[0]), l.split(" ")[1], l.split(" ")[2],
                        new Integer[]{1, 1, 1});

            })
            .collect(Collectors.toList());
}

}

yacmzcpb

yacmzcpb1#

Files.lines返回一个Stream<String>,因此您可以直接在其上链接流方法。
我重写了map步骤,从read行解析Student的字段。
它通过首先删除前导和尾随大括号([])来解析格式为[mark-1, mark-2..., mark-n]的字符串中的标记。然后它在,上拆分字符串,并将每个标记转换为Integer。
在您的代码中,尝试根据正则表达式([0-9])检查提取的标记。如果一个mark/score不是一个Integer,我们不清楚该怎么做,因此我跳过了它,假设我们有有效的数据。

List<Student6> students;
try (Stream<String> fileStream = Files.lines(Paths.get(path1))) {
    students = fileStream.filter(line -> !line.startsWith("#"))
            .map(line -> {
                String[] parts = line.split(" ");
                String marksData = parts[3];
                String marksAsString = marksData.substring(1, marksData.length() - 1); // remove '[' and ']'
                String[] marks = marksAsString.split(",");
                   
                return new Student6(Integer.parseInt(parts[0]),
                        parts[1], parts[2],  Arrays.stream(marks)
                        .map(Integer::parseInt)
                        .toArray(Integer[]::new));
            })
            .collect(Collectors.toList());
}

相关问题