如何阅读:

时间:2018-12-09 14:11:34

标签: java file io

我有一个这样的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;
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

[更新后的答案]因此,如果知道要忽略的确切单词,则此问题的另一个答案会有所帮助,但是当存在大行且包含大行的文件时,此解决方案将更加准确。

    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 :(得分:0)

以下代码应该起作用:

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:开头的行以及空白行或空行。

我知道代码将这些行写入stdout而不是文件中,但这可以由您自己更改