【发布时间】:2012-07-06 06:42:05
【问题描述】:
以下是我将用于我的项目的代码 sn-p 的一部分。
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 进行 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;
}
}
【问题讨论】:
-
我们能看看你是如何初始化输入流的吗?
-
@LouisWasserman 我已经更新了我的代码。
-
也不要使用StringBuffer。 StringBuilder 在 99% 的情况下是首选(正如它在 Javadoc 中所述)
-
@PeterLawrey 是的,我会改变它,谢谢。
标签: java inputstream outputstream