1

嗯,我有一长串需要重写的数据包大小,我不想手动完成,所以我要为它编写一个程序。

public static OutcommingPacket aClass198_1993 = new OutcommingPacket(68, 8);

这是其中一行的示例,我需要做的是让程序转到 68,将其存储在数据包字符串中,然后获取数字 8,并将其存储在大小字符串中。

到目前为止,这是我的代码。

public class PacketSizeFixer {

public static final String IN = "./out/OldPacketSizes.txt";
public static final String OUT = "./out/PacketSizesFormatted.txt";

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(IN));
    BufferedReader writer = new BufferedReader(new FileReader(OUT));

    String line;
    String packet, size;
    while ((line = reader.readLine()) != null) {
        packet = line.substring(line.indexOf("new OutcommingPacket(", line.indexOf(", ")));
        size = line.substring(line.indexOf(", "), line.indexOf(");"));
    }
}

}

我不确定我这样做是否正确,因为我不断得到一个字符串索引超出范围

请帮忙!

顺便说一句,并非所有数据包都具有相同的名称,有些较长,有些较短,数据包可能是两位数,大小也是如此。请帮忙!

4

3 回答 3

3

您可能会收到此错误,因为找不到您要查找的子字符串(返回 -1),然后您在substring不检查返回的索引的情况下调用。
尝试:

int index1 = line.indexOf("new OutcommingPacket(");
int index2 = line.indexOf(", ");
if (index1 > -1 && index2 > index1)
   packet = line.substring(index1, index2 - index1);
//same for the rest
于 2012-07-12T00:22:05.280 回答
3

我在这里假设很多...

while ((line = reader.readLine()) != null) {
    String pair = line.substring(line.lastIndexOf("("), line.lastIndexOf(")"));
    String values[] = pair.split(","); //values[0] == packet, values[1] == size
}
于 2012-07-12T00:25:18.063 回答
2

从您的示例中,听起来您要提取的信息是:

#,#

那么为什么不直接使用正则表达式呢?

CharSequence inputStr = "new OutcommingPacket(68, 8)";

String patternStr = "(\\d+),(\\d+)";

// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();

if (matchFound) {
    // Get all groups for this match
    for (int i=0; i<=matcher.groupCount(); i++) {
        String groupStr = matcher.group(i);
    }
}

注意:我还没有测试过这个确切的模式,但它至少应该接近正确......

于 2012-07-12T00:32:00.660 回答