在Java ME中读取行

时间:2010-08-05 06:49:35

标签: file-io java-me

Java ME是否允许您从InputStream

中读取一行

2 个答案:

答案 0 :(得分:1)

这并不像听起来那么微不足道。不幸的是,行可以以'\ 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();
    }
}

答案 1 :(得分:0)

它确实如此。通过在循环中调用read()直到找到换行符。