简体   繁体   English

Java-在尝试使用资源时跳过第一行

[英]Java - Skip first line while using try with resources

I need to skip the very first line of what is found in the file. 我需要跳过文件中找到的第一行。 My code: 我的代码:

List<String> readStuff() {
    String pathName = "D:/java/eclipse/someStuff.txt";
    List<String> list = new ArrayList<>();
    try (Stream<String> lines = Files.lines(Paths.get(pathName))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        System.out.println("Failed to load file.");
    }
    return list;
}

You can just invoke skip(n) to skip the first n-th element from the stream. 您只需调用skip(n)即可跳过流中的第n个元素。 In this case, using skip(1) would skip the first line. 在这种情况下,使用skip(1)将跳过第一行。

try (Stream<String> lines = Files.lines(Paths.get(pathName))) {
    return lines.skip(1).collect(Collectors.toList());
}

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

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