问题描述
以下是我将用于项目的代码段的一部分.
Following is a part of the code snippet that I will be using for my project.
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块.
Initially the while loop start working pretty fine. But after the probable last character is read from the stream I was expecting to get -1 return value. But this is where my problem starts. The code gets hanged, even the finally block is not executed.
我正在Eclipse中调试此代码,以查看运行时实际发生的情况.我在while循环中设置了一个指针(调试),并不断监视StringBuffer逐一填充char值.但是突然在检查while循环中的条件时,调试控件丢失了,这就是代码进入挂起状态的地方!也不例外!!
I was debugging this code in Eclipse to see what is actually happening during the run-time. I set a pointer (debug) inside the while loop and was constantly monitoring the StringBuffer getting populated with char values one by one. But suddenly while checking the condition inside the while loop, the debugging control is getting lost and this is the point where the code goes to hangup state !! No exception is thrown as well !!
这是怎么回事?
:
这就是我获取InputStream的方式.基本上,我使用的是Apache Commons Net进行Telnet.
This is how I'm getting my InputStream. Basically I'm using 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;
}
}
推荐答案
查看:
简单来说:如果流结束(例如文件结尾),则read()
立即返回-1.但是,如果流仍处于打开状态,但JVM正在等待数据(慢速磁盘,套接字连接),则read()
将阻塞(不是真正挂起).
In simple turns: if your stream ended (e.g. end of file), read()
returns -1 immediately. However if the stream is still open but JVM is waiting for data (slow disk, socket connection), read()
will block (not really hung).
您从哪里获得信息流?查看 available()
-但是请不要在耗尽CPU的循环中调用它.
Where are you getting the stream from? Check out the available()
- but please do not call it in a loop exhausting CPU.
最后:将int
/byte
强制转换为char
仅适用于ASCII字符,请考虑在InputStream
顶部使用Reader
.
Finally: casting int
/byte
to char
will only work for ASCII characters, consider using Reader
on top of InputStream
.
这篇关于InputStream问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!