使用分隔符解析文本字符串

时间:2017-03-06 20:00:28

标签: java text maps

我有一个文本文件:

结构:

key1: xxx
key2: 
key3: 
key4: 
key5:value5
key6: This is an example text file to add data 
       this is an example text file 
       this is an example text file
       this is an example text file
key7:

我试图解析它,但发现难以使用分隔符进行分割':'并添加到地图,以便我可以访问基于键的值。我试过下面的代码。问题是key6,其中有一个段落,并且代码尝试在每个新行之后使用分隔符进行拆分。非常感谢任何帮助处理这个问题。

try{
    Map<Object, Object> map = new Properties();
    BufferedReader br = new BufferedReader
    (new FileReader(textString));      
        String line = "";
        while ((line = br.readLine()) != null) {
            String fields[] = line.split(":");
            map.put(fields[0], fields[1]);
        }
        br.close();
    }catch(Exception e){
    LOGGER.debug("Exception", e);
}

2 个答案:

答案 0 :(得分:1)

因为您在阅读每一行后进行拆分。为什么不解析整个文本,然后执行拆分。喜欢这个

try{
    Map<Object, Object> map = new Properties();
    BufferedReader br = new BufferedReader
    (new FileReader(textString));      
        StringBuffer text = new StringBuffer();
        while (br.readLine() != null) {
            text.append(br.readLine());         
        }
        br.close();


     String fields[] = text.toString().split(":");
        for(int i=0; i < fields.length-1; i++){
            map.put(fields[0], fields[1]);
        }
    }catch(Exception e){
    LOGGER.debug("Exception", e);
}

注意

如果任何值包含冒号,它将破坏您的数据。使用此解决方案或您当前正在做的事情。理想情况下,如果可以的话,将使用java的Properties类部分。

答案 1 :(得分:0)

如果要将其用作键值并将其存储到地图中。然后不要使用:use =。对于下一行值,您可以使用\符号,它将从下一行中获取值。

属性文件:

key1= xxx
key2= 
key3= 
key4= 
key5=value5
key6= This is an example text file to add data \
       this is an example text file \
       this is an example text file \
       this is an example text file
key7=

如何获取值

public static void main(String[] args) throws IOException
    {
         Map<String, String> map = new HashMap<String, String>();
        Properties properties = new Properties();
        properties.load(Main.class.getResourceAsStream("prop.properties"));

        for (final Entry<Object, Object> entry : properties.entrySet()) {
            map.put( (String)entry.getKey(), (String) entry.getValue());
        }

        for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
            Entry type = (Entry) iterator.next();
            System.out.println(type.getKey());
            System.out.println(type.getValue());

        }
    }

<强>输出:

key1
xxx
key2

key5
value5
key6
This is an example text file to add data this is an example text file this is an example text file this is an example text file
key3

key4

key7