从文本文件中读取一组值

时间:2016-06-21 09:43:46

标签: java

{  
   "TEST":"189456",
   "TEST1":"X_Y_Z",
   "TEST2":"Y_Z_W",
   "TEST3":"GGG  ",
   "TEST4":"32423423233322"
},
{  
   "TEST":"123456",
   "TEST1":"X_E_Z",
   "TEST2":"T_Z_W",
   "TEST3":"EWE ",
   "TEST4":"324234243234"
}

这是我想阅读的.txt文件,只能从上面的文件中打印 189456,123456 。任何人都可以帮我这样做。请找代码参考。请发送发布最简单的代码.....

  Pattern p = Pattern.compile("\"Test\"\\s*:\\s*\"(.*)\"", Pattern.CASE_INSENSITIVE);

        while ( (line = bf.readLine()) != null) {
            linecount++;

            Matcher m = p.matcher(line);

            // indicate all matches on the line
            while (m.find()) {

                 System.out.println(m.group(1));
            }
        }

5 个答案:

答案 0 :(得分:2)

另一种方法:

while ((line = br.readLine()) != null) {
    if(line.contains("\"TEST:\"")){
        String[] lineValues = line.split(":");
        System.out.println(lineValues[1].replace("\"", "").replace(",",""));        
    }     
}

答案 1 :(得分:1)

至于正则表达式解决方案:

<receiver android:name=".receiver.SMSReceiver">
            <intent-filter android:priority="999">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

请注意(.*)\"TEST":\"(.*?)\" ,它会使您的正则表达式在?的第一个匹配位置停止。

中间有空格:

"

答案 2 :(得分:1)

使用提供的输入,您应该将其读作json而不是原始文本。

com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
        List<TestObj> test = new ArrayList<TestObj>();
        test = mapper.readValue(new File("c:\\YourFile.txt"), test.getClass());

TestObj是这样的:

class TestObj {
    String test;
    String test1;   // You should use json annotation here because it does not match your json field name.
    ...
    // getter setter methods
}

答案 3 :(得分:0)

希望我能以正确的方式理解这个问题:D

String saveData;
Pattern p = Pattern.compile("\"Test\"\\s*:\\s*\"(.*)\"", Pattern.CASE_INSENSITIVE);

while ( (line = bf.readLine()) != null) {
    linecount++;

    Matcher m = p.matcher(line);

    // indicate all matches on the line
    if(line.contains("189456") || line.contains("123456"))  {
        saveData = line;
    }    
}

如果从readLine()获得的字符串包含搜索到的字符串,则会将其保存在saveData

答案 4 :(得分:0)

    FileInputStream fstream = new FileInputStream("D:\\prac\\src\\test.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

    String strLine;
    while ((strLine = br.readLine()) != null)   {
        if(strLine.contains("\"TEST\":")){
            System.out.println(strLine.split(":")[1].replaceAll("\"","").replace(",",""));
        }
    }

    br.close();
}

输出:

189456
123456