2012-07-12 108 views
1

那麼我有一個龐大的數據包大小的列表需要重新編寫,我不想手動做,所以我要去爲它制定計劃。在Java中的字符串操作導致「字符串索引超出範圍」

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(");")); 
    } 
} 

} 

我不確定是不是我做了正確的方式,因爲我不斷收到一個字符串索引超出範圍

請幫助!

順便說一句,並非所有的數據包都有相同的名稱,有些更長,有些更短,數據包可能是兩位數,並且尺寸也是如此。請幫忙!

+0

請張貼實際的異常和堆棧跟蹤你的問題的一部分。這是那些本地化的調試問題之一,如果人們可以看到問題,那麼這些問題可能會立即解決。 – 2012-07-12 00:30:23

+1

'輸出'拼寫爲'm'。您正在爲作家使用Reader。如果未找到子字符串,則忽略indexOf的-1返回值。您需要將要搜索的字符串的長度添加到子字符串調用的起始索引。 – 2012-07-12 01:45:40

回答

3

我假設這裏有很多...

while ((line = reader.readLine()) != null) { 
    String pair = line.substring(line.lastIndexOf("("), line.lastIndexOf(")")); 
    String values[] = pair.split(","); //values[0] == packet, values[1] == size 
} 
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 
+0

也沒有工作。 – 2012-07-12 00:27:01

+0

add:'System.out.println(「index1 =」+ index1 +「; and index2 =」+ index2);'只是爲了確保...... – alfasin 2012-07-12 00:28:38

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); 
    } 
} 

注:我沒有測試過這個確切的模式,但它應該是接近至少需要更正

+0

我認爲,因爲OP解析了看起來是Java代碼的東西輸入將遇到格式器將部分代碼包裝到下一行的問題。我也認爲模式字符串需要確保它只能找到位於指定構造函數模式中的數字,以及處理Java允許空白的可能的空白區域。當然,最後一點與OP的方法完全不符。 – 2012-07-12 00:39:26

相關問題