【问题标题】:How to read every line after :如何阅读之后的每一行:
【发布时间】:2018-12-09 14:11:34
【问题描述】:

我有一个这样的 TXT 文件:

Start: Here is a random introduction.

Items:
Item 1
Item 2
Item 3
Item 4

End: Here is a random outro.

我想检索第 1 项、第 2 项、第 3 项、第 4 项并将它们放入像 HashMap 这样的数据结构中。我怎样才能做到这一点?

这是我迄今为止尝试过的:

public static void main(String[] args) {
        Scanner scanner = null;

        while (scanner.hasNext()) {
            String line = scanner.nextLine();

            if (line.startsWith("Start:")) {
                String time = line.substring(6);
            }

            if (line.matches("Items:") && scanner.hasNextLine()) {
                String items = line;
            }
        }
    }

【问题讨论】:

  • 显示文件中的行示例
  • @user7294900 项目: - 项目 1 - 项目 2 - 项目 3
  • 你的代码有什么问题?
  • @Jens 我不知道如何只“保存”文件的某些行。例如这里我只想拥有第 1 项、第 2 项、第 3 项和第 4 项以及我不需要的其余行。

标签: java file io


【解决方案1】:

[更新的答案]因此,如果知道要忽略的确切单词但是当有一个包含很多行的大文件时,这个问题的另一个答案会很有帮助,而不是这个解决方案会更准确。

    public static void main(String[] args) {
    // TODO Auto-generated method stub
     String line = "";
     String[] parts = null;
     HashMap<String, String> hashmap=new HashMap<String, String>();

     try {
            BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
            //line = br.readLine();

            while (line != null) {
            line = br.readLine();
           //System.out.println(line.toString());
          if(line!=null){
                //System.out.println(line);

              if(line.contains("Item")&& line.substring(0, 5).compareTo("Item ")==0){        
                    addToHashMap(line,hashmap);
                    System.out.println(line);

              }
          }     
}
            br.close();
            }catch(IOException ioe){
                System.err.println(ioe.getMessage());

}

}

private static  void addToHashMap(String line, HashMap<String,String> hashMap) {
    // TODO Auto-generated method stub
    Random random=new Random();
    hashMap.put(Integer.toString(random.nextInt(100)), line);       

     }

【讨论】:

  • 谢谢!我忘了提到我只需要这个文本文件的某些部分。这是一个文本文件示例,我只需要以下几行:第 1 项、第 2 项、第 3 项:这是一个随机介绍。项目:项目 1 项目 2 。第 3 项。第 4 项。这是一个随机的结尾。
  • 现在只有带有单词“Item”的行会被选中。
【解决方案2】:

以下代码应该可以工作:

public static void main(String[] args) {
    Scanner scanner = new Scanner(TestCdllLogger.class.getResourceAsStream("/test.txt"));

    while (scanner.hasNext()) {
        String line = scanner.nextLine();

        if (line.startsWith("Start:") || line.startsWith("End:") || line.startsWith("Items:") || line.startsWith(" ") ||line.isEmpty() ) {
            continue;
        }

        System.out.println(line);
    }
}

它会忽略所有以Start:、End:、Items: 开头的行以及空白行。

我知道代码将行写入标准输出而不是文件,但这可以由您自己更改

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2012-03-15
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多