0

Apache telnet使用InputStream,我想将其读取为字符串(或类似字符串的数据)。

我怎样才能把它InputStream变成更容易(对我来说)处理的东西,aStringBuffer或类似的东西。

4

3 回答 3

2

You can consider IOUtils.toString(is) from Apache Common IO

public static String toString(InputStream input)
                       throws IOException

from the doc:

This method buffers the input internally, so there is no need to use a BufferedInputStream.

于 2013-08-28T06:39:57.807 回答
1

You cant transform the InputStream into StringBuffer. But if you want to make use of StringBuffer then you can read the input from InputStream as a int and append it to StringBuffer like below.

int i=fis.read(); //it will read Character from stream and returns ascii value of char.
StringBuffer sb=new StringBuffer();
sb.append((char)i); //This will cast int into character and append to StringBuffer.
于 2013-08-28T06:40:01.360 回答
0

这是其中的一部分:

package teln;

import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import org.apache.commons.net.telnet.TelnetClient;

public final class ConnectMUD {

    private static String EOL = "/[#]/";
    private static TelnetClient tc;

    public static void main(String[] args) throws SocketException, IOException {
        tc = new TelnetClient();
        tc.connect("some_mud.com", 123);
        readLines(tc.getInputStream());
    }

    private static void readLines(InputStream in) throws IOException {

        InputStreamReader is = new InputStreamReader(in);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(is);
        String read = br.readLine();

        while (read != null) {
            out.println(read);
            sb.append(read);
            read = br.readLine();
            parseLine(read);
        }
    }

    private static void parseLine(String read) {
        login(read);
    }

    private static void login(String read) {
        //hmm, how do you know when you
        //get some funky, non-standard login?
        //look for an EOL of some sort?
    }
}

那里可能会出现一些非常大的字符串,但我首先关注的是功能。只是试图开始解析播放 da MUD 的行。

于 2013-08-28T07:17:45.753 回答