2010-08-05 3 views

답변

0

소리처럼 사소하지는 않습니다. 불행히도, 줄은 '\ r', '\ n'또는 '\ r \ n'으로 끝날 수 있습니다. 다음 클래스는 이러한 모든 경우를 처리합니다.

public class LineReader{ 
    private Reader in; 
    private int bucket=-1; 
    public LineReader(Reader in){ 
     this.in=in; 
    } 

    public boolean hasLine() throws IOException{ 
     if(bucket!=-1)return true; 
     bucket=in.read(); 
     return bucket!=-1; 
    } 

    //Read a line, removing any /r and /n. Buffers the string 
    public String readLine() throws IOException{ 
     int tmp; 
     StringBuffer out=new StringBuffer(); 
     //Read in data 
     while(true){ 
      //Check the bucket first. If empty read from the input stream 
      if(bucket!=-1){ 
       tmp=bucket; 
       bucket=-1; 
      }else{ 
       tmp=in.read(); 
       if(tmp==-1)break; 
      } 
      //If new line, then discard it. If we get a \r, we need to look ahead so can use bucket 
      if(tmp=='\r'){ 
       int nextChar=in.read(); 
       if(tmp!='\n')bucket=nextChar;//Ignores \r\n, but not \r\r 
       break; 
      }else if(tmp=='\n'){ 
       break; 
      }else{ 
       //Otherwise just append the character 
       out.append((char) tmp); 
      } 
     } 
     return out.toString(); 
    } 
} 
0

예 : 개행이 발견 될 때까지 루프에서 read()를 호출함으로써.

관련 문제