2012-02-10 3 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); 
     } 
    } 

나는 공백의 라인을 읽을 때 나는 문자열을 얻을 그러나 라인이 필요합니다 있는지 확인하기 위해 특정 인덱스에 공백 라인 (뿐만 아니라 공백)와 비교 문자와 파일에 읽고있다 범위를 벗어난 색인자바의 readline 공백

+2

문제를 설명하는 코드를 제공해 줄 수 있습니까? –

+0

당신을 도울 수있는 몇 가지 코드가 필요합니다 ... – debracey

답변

2

줄의 길이가 0이고 위치 10의 문자를 확인하려는 경우 예를 들어 예외가 발생합니다. 처리하기 전에 라인이 공백이 아닌지 확인하기 만하면됩니다.

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

빈 줄은 null이 아니며 빈 문자열 ''입니다. 당신이 색인 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); 
    } 
} 

또한 자바 스캐너 종류를 시도하고 이용하기 위하여 시도 할 수있다. 파일을 읽는 데 정말 유용합니다.

0

여기에서하는 일은 String strLine에는 많은 문자가 없을 수 있지만 strLine.charAt(25)을 사용하여 25 번째 문자까지 헌장을 확인하는 것입니다. index 인수가이 문자열의 길이보다 작지 않으면 charAt(int index) 메서드는 IndexOutOfBoundsException을 반환합니다.

당신은 strLine.length()를 호출하여 strLine의 길이를 찾은 다음 strLine.length() - 10에서 charAt()을 확인하고 해당 예외를 볼 수 없습니다 수 있습니다.