有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java同时读取输入流

我开发了一个j2me应用程序,通过socket连接到我的网络主机服务器。我使用自己的扩展lineReader类从服务器读取响应,该类扩展了基本InputStreamReader。如果服务器发送5行回复,则逐行读取服务器回复的语法为:

        line=input.readLine();
        line = line + "\n" + input.readLine();
        line = line + "\n" + input.readLine();
        line = line + "\n" + input.readLine();
        line = line + "\n" + input.readLine();

在这种情况下,我可以编写这种语法,因为我知道回复的数量是固定的。但是,如果我不知道行数,并且想要一次读取整个inputStream,我应该如何修改当前的readLine()函数。下面是函数的代码:

public String readLine() throws IOException {
    StringBuffer sb = new StringBuffer();
    int c;
    while ((c = read()) > 0 && c != '\n' && c != '\r' && c != -1) {
        sb.append((char)c);
    }
    //By now, buf is empty.
    if (c == '\r') {
        //Dos, or Mac line ending?
        c = super.read();
        if (c != '\n' && c != -1) {
            //Push it back into the 'buffer'
            buf = (char) c;
            readAhead = true;
        }
    }
    return sb.toString();
}

共 (2) 个答案

  1. # 1 楼答案

    如果我理解正确,您可以使用一个简单的循环:

    StringBuffer sb = new StringBuffer();
    String s;
    while ((s = input.readLine()) != null)
        sb.append(s);
    

    在循环中添加计数器,如果计数器=0,则返回null:

    int counter = 0;
    while ((c = read()) > 0 && c != '\n' && c != '\r' && c != -1) {
        sb.append((char)c);
        counter++;
    }
    if (counter == 0)
        return null;
    
  2. # 2 楼答案

    那Apache Commons IOUtils.readLines()

    Get the contents of an InputStream as a list of Strings, one entry per line, using the default character encoding of the platform.

    或者如果你只需要一个字符串,可以使用IOUtiles.toString()

    Get the contents of an InputStream as a String using the default character encoding of the platform.

    [update]根据关于J2ME上可以使用这一点的评论,我承认我忽略了这个条件,但是IOUtils source对依赖项的依赖性非常轻,所以也许代码可以直接使用