监视输入流的最佳方法是什么?
我正在通过 apache.commons.FtpClient 读取文件。
这在 99.9% 的情况下都可以正常工作,但有时它会在 read() 方法中死掉……
InputStream inStream = ftp.retrieveFileStream(path + file.getName());
String fileAsString = "";
if(inStream == null){
return;
}
while((c = inStream.read()) != -1){ //this is where the code sometimes just hangs
fileAsString += Character.valueOf((char)c);
}
我的问题是,防止无限期锁定系统的最可靠方法是什么。 我应该在单独的线程中设置计时器吗? 或者有更简单的方法吗?
I'm reading a file in via apache.commons.FtpClient.
This works fine 99.9% of the time but sometimes it just dies in the read() method...
InputStream inStream = ftp.retrieveFileStream(path + file.getName());
String fileAsString = "";
if(inStream == null){
return;
}
while((c = inStream.read()) != -1){ //this is where the code sometimes just hangs
fileAsString += Character.valueOf((char)c);
}
My question is what is the most reliable way to protect against this locking up the system indefinitely. Should I be setting a timer in a separate thread? Or is there a simpler way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的代码挂起,则意味着您的 FTP 服务器尚未发送整个文件。 您可以使用计时器,但我相信 FtpClient 允许您设置超时。
顺便说一句:您读取文件的方式非常效率低下。 如果您的文件大于几 K,它将使用越来越多的 CPU。
您正在从一个字节创建一个字符(这本身就是一个坏主意),并为文件中的每个字节创建一个字符串对象。
我建议使用提供的复制方法或 commons-io 库附带的方法将数据复制到 ByteArrayInputStream。
If your code hangs it means your FTP server has not sent the entire file. You can use a Timer, but I believe FtpClient allows you to set a timeout.
BTW: the way you read the file is very inefficient. If your file is larger than a few K it will use increasing amounts of CPU.
You are creating a Character from a byte (which is a bad idea in itself) and a String object for every byte in the file.
I suggest using the copy method provided or the one which comes with commons-io library to copy the data to a ByteArrayInputStream.
快速浏览一下文档,如果您这样做了...
它似乎会在您实际阅读之前仔细检查您是否可以无阻塞地阅读。 不过我对此并不确定。
Just from a quick look at the docs, if you did...
It seems like it would double check that you can read without blocking before you actually read. I'm not certain on this though.