2015-11-10 74 views
1

我不知道它爲什麼。我一行一行地讀取我的文本文件,通過分割來剪切行並將它們保存到一個ArrayList。但是如果文件長度超過100行,我的程序將無法工作,因此它會在分割命令時返回錯誤。我想知道我的電腦是否內存不足?爲什麼ArrayList返回錯誤:ArrayIndexOutOfBoundsException

大家,誰能說得通?先進的謝謝你。 這裏是我的代碼:

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.Collections; 
import javax.swing.JOptionPane; 
class Vocab implements Comparable<Vocab>{ 
    private String vocab; 
    private String explanation; 
    public Vocab(String vocab, String explanation) { 
     this.vocab = vocab; 
     this.explanation = explanation; 
    } 
    public int compareTo(Vocab that){ 
     return this.vocab.compareTo(that.vocab); 
    }  
    public String getVocab() { 
     return vocab; 
    } 
    public void setVocab(String vocab) { 
     this.vocab = vocab; 
    } 
    public String getExplanation() { 
     return explanation; 
    } 
    public void setExplanation(String explanation) { 
     this.explanation = explanation; 
    } 
} 
public class Test { 
    public static void readFile(String fileName, ArrayList<String> a) throws FileNotFoundException { 
     try { 
      File fileDir = new File(fileName); 
      BufferedReader in = new BufferedReader(
       new InputStreamReader(
        new FileInputStream(fileDir), "UTF8")); 
     String str; 
     while((str= in.readLine())!= null){ 
       a.add(str);     
     } 
     in.close(); 
     }   
     catch (IOException e) 
     { 
      JOptionPane.showMessageDialog(null,"Something in database went wrong"); 
     }      
    }   
    public static void main(String[] args) throws FileNotFoundException { 
     // TODO code application logic here 
     ArrayList<Vocab> a= new ArrayList<Vocab>(); 
     ArrayList<String> b= new ArrayList<String>(); 
     readFile("DictVE.dic",b); 
     for (String t: b){ 
      String[] temp= t.split(":"); 
      a.add(new Vocab(temp[0].trim(), temp[1].trim()));// error in here 
     } 
    }  
} 

,這裏是我的文件:DictEV.dic

+1

是否確定所有行都有「:」? – ParkerHalo

+0

@KevinEsche文件的每一行總是有「:」字符。我已經定義了它,你可以在我的線程末尾查看它們。 –

+2

是否有任何字符串以':'結尾? –

回答

4

有一個微妙的疑難雜症在String.split(String) method,這是空令牌從字符串的結尾丟棄:

Trailing empty strings are therefore not included in the resulting array.

所以:

System.out.println("Hello:".split(":").length); // Prints 1. 

您可以通過傳遞負int作爲第二個參數來保留空字符串:

System.out.println("Hello:".split(":", -1).length); // Prints 2. 
+0

非常感謝你! –

相關問題