0

我从 a 得到了一个文本BufferedReader,我需要在一个特定的字符串中获取一个特定的值。

这是文本:

    aimtolerance = 1024;
    model = Araarrow;
    name = Bow and Arrows;
    range = 450;
    reloadtime = 3;
    soundhitclass = arrow;
    type = Ballistic;
    waterexplosionclass = small water explosion;
    weaponvelocity = 750;

        default = 213;
        fort = 0.25;
        factory = 0.25;
        stalwart = 0.25;
        mechanical = 0.5;
        naval = 0.5;

我需要得到 default =;之间的确切数字

这是“213”

4

5 回答 5

3

像这样的东西......

String line;
while ((line = reader.readLine())!=null) {
   int ind = line.indexOf("default =");
   if (ind >= 0) {
      String yourValue = line.substring(ind+"default =".length(), line.length()-1).trim(); // -1 to remove de ";"
      ............
   }
}
于 2012-07-20T15:27:29.620 回答
0

If just care about the end result, i.e. getting stuff out of your '=' separated values text file, you might find the built in Properties object helpful?

http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html

This does much of what you need. Of course if you're specifically wanting to do this manually, it's maybe not the right option.

于 2012-07-20T15:24:40.963 回答
-1

在“default =”上拆分字符串,然后使用 indexOf 查找“;”的第一次出现。做一个从 0 到索引的子字符串,你就有了你的价值。

请参阅http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

于 2012-07-20T15:23:43.060 回答
-1

您可以使用Properties类来加载字符串并从中找到任何值

String readString = "aimtolerance = 1024;\r\n" + 
"model = Araarrow;\r\n" + 
"name = Bow and Arrows;\r\n" + 
"range = 450;\r\n" + 
"reloadtime = 3;\r\n" + 
"soundhitclass = arrow;\r\n" + 
"type = Ballistic;\r\n" + 
"waterexplosionclass = small water explosion;\r\n" + 
"weaponvelocity = 750;\r\n" + 
"default = 213;\r\n" + 
"fort = 0.25;\r\n" + 
"factory = 0.25;\r\n" + 
"stalwart = 0.25;\r\n" + 
"mechanical = 0.5;\r\n" + 
"naval = 0.5;\r\n";
readString = readString.replaceAll(";", "");
Properties properties = new Properties();

System.out.println(properties);
try {
    properties.load(new StringReader(readString));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println(properties);

String requiredPropertyValue = properties.getProperty("default");
System.out.println("requiredPropertyValue : "+requiredPropertyValue);
于 2012-07-21T17:50:09.407 回答
-1

使用正则表达式:

private static final Pattern DEFAULT_VALUE_PATTERN
        = Pattern.compile("default = (.*?);");

private String extractDefaultValueFrom(String text) {
    Matcher matcher = DEFAULT_VALUE_PATTERN.matcher(text);
    if (!matcher.find()) {
        throw new RuntimeException("Failed to find default value in text");
    }
    return matcher.group(1);
}
于 2012-07-20T15:44:50.683 回答