以下是我将用于我的项目的代码片段的一部分。InputStream的问题
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>>>>>>>>>>>>>>>>>>>>>>>>>>>");
}
}
最初while循环开始工作很好。但是在从流中读取可能的最后一个字符后,我期望得到-1返回值。但这是我的问题开始的地方。代码被挂起,即使finally块也不会被执行。
我在Eclipse中调试此代码以查看运行期间实际发生的情况。我在while循环中设置了一个指针(调试),并不断监视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;
}
}
我们能否看到如何初始化输入流? – 2012-07-05 19:46:47
@LouisWasserman我已更新我的代码。 – 2012-07-05 19:57:07
也不要使用StringBuffer。在99%的案例中,StringBuilder是首选(因为它在Javadoc中声明) – 2012-07-05 19:59:09