2014-12-03 51 views
0

我想讀取一個文件並逐行分割字符串的行。這是文件中的示例字符串避免數組索引超出綁定異常,而拆分字符串

Decorative Platters--------Home & Kitchen->Home & Décor->Home Décor Accents 
Hookah--------Watches & Jewellery->Fashion Jewellery->Bangles 
hookah-------- 

在這種情況下,第三行在點後沒有任何內容。

private static void getCategoriesFromFileAndMAtch() { 
    try { 
     BufferedReader br=new BufferedReader(new FileReader("mapping_log")); 
     String eachLine; 
     while((eachLine = br.readLine()) != null) 
     { 
      String input1, input2, tempString; 
      input1=eachLine.split("--------")[0]; 
      tempString=eachLine.split("--------")[1]; 
      if(!(eachLine.split("--------")[1].isEmpty())) 
      { 
       tempString=eachLine.split("--------")[1].split("::=>")[0]; 
       System.out.println(input1+" "+tempString); 
      } 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace();   
    } 

} 

因爲[1]的值爲空我收到異常並且程序停止。我怎樣才能避免這種情況?我檢查它是否爲空或不在if循環中。這還不夠嗎?

回答

2

當您編寫以下代碼行時,假定元素存在,但在您的情況下根本不存在,並且if語句本身隨異常而爆發。

if(!(eachLine.split("--------")[1].isEmpty())) 

相反,檢查split()返回值的長度。

if(eachLine.split("--------").length > 1) 
+0

我想你想'如果(eachLine.split(「--------」)。長度> 1)'那裏 - 'length'是數組的屬性,而不是方法。 (太小的修復提交編輯。) – Ben 2014-12-03 05:49:39

+0

@本,謝謝!我修好了它。 – merlin2011 2014-12-03 05:55:55

1

建議:

  1. 不要做tempString = eachLine.split( 「--------」);多次,每次執行該操作時,都會一遍又一遍地分割(昂貴的操作)。因此,總是,分割一次,並嘗試重新使用下面示例中提到的結果。
  2. 在數組長度未知的情況下,使用array.length找出它並添加適當的條件。

樣品:

String input1, input2, tempString; 
String [] parts = eachLine.split("--------"); 
input1 = parts[0]; 

if (parts.length > 1) { 
    input2 = parts[0]; 
    tempString=input2.split("::=>")[0]; 
    System.out.println(input1 + " " + tempString); 
} 
0

對於第三種情況,eachLine.split("--------")將返回數組長度爲1,所以當你訪問數組索引1,即 eachLine.split("--------")[1]它給出了一個例外。您可以拳頭檢查,如果通過分割函數返回的數組大於1

if(eachLine.split("--------").length > 1 && !(eachLine.split("--------")[1].isEmpty())) 
{ 
tempString=eachLine.split("--------")[1].split("::=>")[0]; 
System.out.println(input1+" "+tempString); 
}