2012-02-10 126 views
0
FileInputStream fstream = new FileInputStream("data.txt"); 

// Get the object of DataInputStream 
DataInputStream in = new DataInputStream(fstream); 

BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

String strLine; 
//Read File Line By Line 

while ((strLine = br.readLine()) != null) 
    { 
    //Test if it is a line we need 
    if(strLine.charAt(0) != ' ' && strLine.charAt(5) == ' ' 
     && strLine.charAt(10) == ' ' && strLine.charAt(15) == ' ' 
     && strLine.charAt(20) == ' ' && strLine.charAt(25) == ' ') 
     { 
     System.out.println (strLine); 
     } 
    } 

我正在閱讀一個文件中有空白行(不僅是空白)和比較特定索引的字符以查看我是否需要該行,但是當我讀取一行空白時我得到一個字符串索引超出範圍。Java readline空白

+2

你能提供一些代碼來說明你的問題嗎? – 2012-02-10 04:39:52

+0

需要看一些代碼來幫助你... – debracey 2012-02-10 04:40:16

回答

2

如果該行長度爲0,並且您試圖確定位置10處的字符,例如您將得到一個異常。只需在檢查之前查看該行在處理之前是否不是全部空白。

if (line != null && line.trim().length() > 0) 
{ 
    //process this line 
} 
0

空行不會爲空,而是空字符串''。如果你在索引0

while ((strLine = br.readLine()) != null) 
{ 
    //remove whitespace infront and after contents of line. 
    strLine = strLine.trim(); 

    if (strLine.equals("")) 
     continue; 

    //check that string has at least 25 characters when trimmed. 
    if (strLine.length() <25) 
     continue; 

    //Test if it is a line we need 
    if(strLine.charAt(0) != ' ' && strLine.charAt(5) == ' ' && strLine.charAt(10) == ' ' && strLine.charAt(15) == ' ' && strLine.charAt(20) == ' ' && strLine.charAt(25) == ' ') 
    { 
     System.out.println (strLine); 
    } 
} 

您也可以嘗試使用Java Scanner類嘗試讀取的字符會破。這對於閱讀文件非常有用。

0

你在這裏做的是使用strLine.charAt(25)檢查包機到第25個字符,而你的String strLine可能沒有那麼多字符。 charAt(int index)方法將拋出IndexOutOfBoundsException - 如果index參數不小於此字符串的長度。

你可以通過調用strLine.length()找到strLine的長度,然後從0檢查charAt()strLine.length() - 1,你不會看到異常。