【问题标题】:Detect the end of line in file检测文件中的行尾
【发布时间】:2020-04-08 11:53:15
【问题描述】:

我正在尝试读取txt 文件并显示文件元素。我想在同一行显示元素以给出一个换行符。但是,当文件中的新行开始时,给出额外的新行。 txt 文件是:

星际 % Christopher Nolan % 2014 % PG-13

开始 % Christopher Nolan % 2010 % PG-13

Endgame % Russo Brothers % 2019 % PG-13

这里,% 是分隔符。到目前为止我做了什么:

File file_path = new File("film.txt");
try {
    Scanner file_input = new Scanner(file_path);
    file_input.useDelimiter("%");
    for(new_book=1; file_input.hasNext(); new_book++) {
        String book_item = file_input.next().trim();
        System.out.println(book_item);
        if(new_book%4==0){
            System.out.println();
        }
    }
    file_input.close();
} 
catch (FileNotFoundException e) {
    System.out.println("File not found");
}

它提供了什么:

Interstellar 
Christopher Nolan
2014
PG-13
Inception 

Christopher Nolan
2010
PG-13
Endgame 
Russo Brothers

2019 
PG-13

我想要的是:

Interstellar 
Christopher Nolan
2014
PG-13

Inception 
Christopher Nolan
2010
PG-13

我注意到的是,在行尾索引不起作用,即如果我打印 new_book 那么,new_book 值不会显示在第一个和第二个 PG-13 中,但显示在最后一个 PG-13 .

我对文件中的这一行感到困惑。每一个建议都值得赞赏!!!另外,请注意,我不会与语法错误混淆。但是,与逻辑和文件读取过程是如何完成的。

【问题讨论】:

  • 这真的是您使用的代码吗?
  • 是的,我认为它会起作用。
  • 我认为您没有运行此代码。它缺少结束 } 并使用 - 作为分隔符。它可能在其他方面也与您的真实代码不同。您能否发布一个说明问题的自包含示例?
  • 现在我已经编辑了...谢谢...

标签: java file line file-handling


【解决方案1】:

问题在于换行符不被视为分隔符,因此第 4 个标记被读取为PG-13<NEWLINE>Inception - 其中嵌入了换行符。您的选择是:

添加换行符作为可能的分隔符:

Scanner file_input = new Scanner(file_path);
file_input.useDelimiter("%|\n");

或者在输入文件的每一行末尾添加 %:

星际 % Christopher Nolan % 2014 % PG-13 %
启动 % Christopher Nolan % 2010 % PG-13 %

或将文件读取方式更改为逐行读取并在%上拆分(参见其他人的答案)

【讨论】:

    【解决方案2】:

    您可以尝试读取该行,然后将其拆分

    file_input = new Scanner(file);
    while(file_input.hasNextLine()){
        String st = file_input.nextLine();
        String[] s = st.split("%");
        if(s.length > 1)
            System.out.println(s[0] + "\n" + s[1] + "\n" + s[2] + "\n" + s[3] + "\n");
    }
    file_input.close();
    

    【讨论】:

      【解决方案3】:

      我使用scanner.nextLine() 函数一次读取整行。然后我使用 String.split("%") 将行字符串拆分为字符串列表。最后,我在输出之前对每个字符串使用了 String.trim() 以删除前导和尾随空格。

      File file_path = new File("film.txt");
      try {
          Scanner file_input = new Scanner(file_path);
          while(file_input.hasNextLine()){
              String line = file_input.nextLine();
              String[] items = line.split("%");
      
              for(String item: items)
                  System.out.println(item.trim());
      
              System.out.println();
      
          }
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }
      

      【讨论】:

        猜你喜欢
        • 2012-08-23
        • 2014-07-08
        • 1970-01-01
        • 2010-09-07
        • 2011-06-02
        • 1970-01-01
        • 2015-11-22
        • 1970-01-01
        • 2012-12-08
        相关资源
        最近更新 更多