为了账号安全,请及时绑定邮箱和手机立即绑定

如何跳过文件的第一行?

如何跳过文件的第一行?

吃鸡游戏 2023-07-28 16:43:16
我从文件中读取并存储在数组中,文件的第一行仅包含&ldquo;1&rdquo;,第二行包含从空格键分割的字典单词。那么如何从第二行读取文件呢?try        {         File text = new File ("dictionary.txt");         Scanner file = new Scanner(new File("dictionary.txt"));         while(file.hasNextLine())         {          System.out.println("Level 1");           int level1 = file.nextInt();           file.nextLine();           for(int i = 1; i < 7; i++)            {             String [] array = content.split(" ");             String A = array[0];             String B = array[1];             String C = array[2];            System.out.println(B);           }         }         file.close();        }文件的格式是1
查看完整描述

2 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

只需使用计数器


int count = 0;

while(file.hasNextLine())

{

    count++;

    if (count <= 1) {

      file.nextLine ();

      continue;

    }

    ....

}


查看完整回答
反对 回复 2023-07-28
?
慕妹3242003

TA贡献1824条经验 获得超6个赞

我实际上会使用text而不是重新定义File来构造Scanner. 更喜欢try-with-Resources显式关闭Scanner. 实际上分配content,不要硬编码数组迭代的“魔法值”。基本上,类似


File text = new File("dictionary.txt");

try (Scanner file = new Scanner(text)) {

    if (file.hasNextLine()) {

        file.nextLine(); // skip first line.

    }

    while (file.hasNextLine()) {

        String content = file.nextLine();

        if (content.isEmpty()) {

            continue; // skip empty lines

        }

        String[] array = content.split("\\s+");

        for (int i = 0; i < array.length; i++) {

            System.out.println(array[i]);

        }

    }

} catch (Exception e) {

    e.printStackTrace();

}

如果使用 Java 8+,另一种选择是使用流式Files.lines(Path)传输所有行(和skip(1)),例如


File text = new File("dictionary.txt");

try {

    Files.lines(text.toPath()).skip(1).forEach(content -> {

        if (!content.isEmpty()) {

            System.out.println(Arrays.toString(content.split("\\s+")));

        }

    });

} catch (IOException e) {

    e.printStackTrace();

}


查看完整回答
反对 回复 2023-07-28
  • 2 回答
  • 0 关注
  • 76 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信