InputStream的问题

Sub*_*Roy 2 java inputstream outputstream

以下是我将用于我的项目的代码片段的一部分.

public String fetchFromStream()
{
    try
    {
        int charVal;
        StringBuffer sb = new StringBuffer();

        while((charVal = inputStream.read()) > 0) {
            sb.append((char)charVal);
        }
        return sb.toString();
    } catch (Exception e)
    {
        m_log.error("readUntil(..) : " + e.getMessage());
        return null;
    } finally {
        System.out.println("<<<<<<<<<<<<<<<<<<<<<< Called >>>>>>>>>>>>>>>>>>>>>>>>>>>");
    }
}
Run Code Online (Sandbox Code Playgroud)

最初,while循环开始工作得非常好.但是在从流中读取可能的最后一个字符后,我期望获得-1返回值.但这是我的问题开始的地方.代码被绞死,即使finally块也没有被执行.

我在Eclipse中调试此代码以查看运行时实际发生的情况.我在while循环中设置了一个指针(debug),并且一直在监视StringBuffer,逐个填充char值.但是在检查while循环中的条件时突然,调试控件丢失了,这就是代码进入挂断状态的地方!也没有例外!

这里发生了什么?

编辑::

这就是我获取InputStream的方式.基本上我正在使用Apache Commons Net for Telnet.

private TelnetClient getTelnetSession(String hostname, int port)
{
    TelnetClient tc = new TelnetClient();
    try
    {
        tc.connect(hostname, port != 0 ? port : 23);

                    //These are instance variables
        inputStream = tc.getInputStream();
        outputStream = new PrintStream(tc.getOutputStream());

        //More codes...

        return tc;
    } catch (SocketException se)
    {
        m_log.error("getTelnetSession(..) : " + se.getMessage());
        return null;
    } catch (IOException ioe)
    {
        m_log.error("getTelnetSession(..) : " + ioe.getMessage());
        return null;
    } catch (Exception e)
    {
        m_log.error("getTelnetSession(..) : " + e.getMessage());
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*icz 5

看看JavaDocs:

从输入流中读取下一个数据字节.值字节作为int返回,范围为0到255.如果没有字节可用,因为已到达流末尾,则返回值-1.此方法将阻塞,直到输入数据可用,检测到流的末尾或抛出异常.

简单转弯:如果你的流结束(例如文件结束),read()立即返回-1.但是,如果流仍处于打开状态但JVM正在等待数据(慢速磁盘,套接字连接),read()则会阻塞(不会挂起).

你从哪里得到这条小溪?检查available()- 但请不要在耗尽CPU的循环中调用它.

最后:cast int/ byteto char仅适用于ASCII字符,考虑使用Reader在上面InputStream.