在Java ME中读取行 [英] Read lines in Java ME

查看:126
本文介绍了在Java ME中读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java ME允许你从 InputStream 中读取一行吗?

解决方案'或'\r\\\
'结尾。下面的类将处理所有这些情况。

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


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

//读取一行,删除/ r和/ n。缓冲字符串
public String readLine()throws IOException {
int tmp;
StringBuffer out = new StringBuffer();
//读入数据
while(true){
//首先检查桶。如果为空,则从输入流中读取
if(bucket!= - 1){
tmp = bucket;
bucket = -1;
} else {
tmp = in.read();
if(tmp == - 1)break;
}
//如果换行,则放弃它。如果我们得到一个\r,我们需要向前看,所以可以使用桶
if(tmp =='\r'){
int nextChar = in.read();
if(tmp!='\\\
')bucket = nextChar; //忽略\r\\\
,而不是\r\r
break;
} else if(tmp =='\\\
'){
break;
} else {
//否则直接附加字符
out.append((char)tmp);
}
}
返回out.toString();
}
}


Does Java ME allow you to read a line from an InputStream?

解决方案

This is not as trivial as it sounds. Unfortunately, lines could end with '\r', '\n' or '\r\n'. The following class will handle all of these cases.

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();
    }
}

这篇关于在Java ME中读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆