Java - 使用try with resources时跳过第一行 [英] Java - Skip first line while using try with resources

查看:188
本文介绍了Java - 使用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;
}


推荐答案

你可以调用 skip( n) 从流中跳过第一个第n个元素。在这种情况下,使用 skip(1)将跳过第一行。

You can just invoke skip(n) to skip the first n-th element from the stream. In this case, using skip(1) would skip the first line.

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

这篇关于Java - 使用try with resources时跳过第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆