如何跳过文件的第一行?

我从文件中读取并存储在数组中,文件的第一行仅包含“1”,第二行包含从空格键分割的字典单词。那么如何从第二行读取文件呢?


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

吃鸡游戏
浏览 105回答 2
2回答

12345678_0001

只需使用计数器int count = 0;while(file.hasNextLine()){&nbsp; &nbsp; count++;&nbsp; &nbsp; if (count <= 1) {&nbsp; &nbsp; &nbsp; file.nextLine ();&nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; ....}

慕妹3242003

我实际上会使用text而不是重新定义File来构造Scanner. 更喜欢try-with-Resources显式关闭Scanner. 实际上分配content,不要硬编码数组迭代的“魔法值”。基本上,类似File text = new File("dictionary.txt");try (Scanner file = new Scanner(text)) {&nbsp; &nbsp; if (file.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; file.nextLine(); // skip first line.&nbsp; &nbsp; }&nbsp; &nbsp; while (file.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; String content = file.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; if (content.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue; // skip empty lines&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; String[] array = content.split("\\s+");&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < array.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(array[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }} catch (Exception e) {&nbsp; &nbsp; e.printStackTrace();}如果使用 Java 8+,另一种选择是使用流式Files.lines(Path)传输所有行(和skip(1)),例如File text = new File("dictionary.txt");try {&nbsp; &nbsp; Files.lines(text.toPath()).skip(1).forEach(content -> {&nbsp; &nbsp; &nbsp; &nbsp; if (!content.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Arrays.toString(content.split("\\s+")));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });} catch (IOException e) {&nbsp; &nbsp; e.printStackTrace();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java