java用缓冲区从网络输入流中读取(需要排除空符号)

时间:2013-10-30 11:46:56

标签: java networking java-io

我有从网络输入流中读取的方法。

    //pattern value is shell prompt string ":~#"
    //this do read shells output like from command "ls", etc...
    public String readUntil(String pattern) throws IOException, JSchException {
    long began = System.currentTimeMillis();
    long lastTime = System.currentTimeMillis();
    StringBuilder sb = new StringBuilder();
    socket.setTimeout(timeout);
    iks: while (true) {
        try {
            int c = -1;
            byte[] text = new byte[1024];
            c = in.read(text);
            long now = System.currentTimeMillis();
            if (c != -1) {
                sb.append(new String(text));
                lastTime = now;
            }
            if (now - lastTime > timeout){
                System.out.println( "BREAK BY TIMEOUT");
                break;
            }
            if (sb.toString().contains(pattern)) {
                System.out.println( "BREAK BY PATTERN");
                break;
            }
            Thread.sleep(50);
        }catch(Exception e){
            System.out.println("¬"+e);
            break iks;
        }
    }
    System.out.println( "TIME TAKEN readUntil -> "+(System.currentTimeMillis()-began));
    //Log.v("¬","result -> "+sb.toString());
    return sb.toString();
}

这种方法工作得相当快,但每次读取都会使用空值填充字节数组的结尾。怎么做“sb.append(new String(text));”排除空字节?

2 个答案:

答案 0 :(得分:2)

您的读取逻辑有问题,因为您分配了1024的缓冲区(所有成员初始化为null),然后在最后一次传递时,显然缓冲区的某些部分可以保持为空,从而导致写入空值。

因此,您需要在到达流的末尾后停止阅读,尝试按以下方式更改代码:

byte[] buff = new byte[255];

    String output = "";
    InputStream is = //get input stream

    int n = 0;
    while ( (n = is.read(buff) )!=-1)
    {
        output += new String(buff,0,n);
    }

    is.close();

通过这种方式,您将获得仅具有初始化缓冲区成员的字符串,“n”的值是实际读取的字节数(=无空值)。您可以根据需要更改读取块。

答案 1 :(得分:0)

尝试在代码中使用BufferedInputStream - > BufferedInputStream(InputStream in)

方法read(byte[] b, int off, int len)从该字节输入流中读取字节到指定的字节数组,从给定的偏移量开始,并返回读取的字节数,如果已达到流的末尾,则返回-1

你的代码中的

将是:

BufferedInputStream bis = new BufferedInputStream(in);
...
byte text[] = new byte[]; // size of byte array can change
c = bis.read(text, 0, 1024);