监视输入流的最佳方法是什么?

发布于 2024-07-14 11:25:57 字数 470 浏览 3 评论 0原文

我正在通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你是年少的欢喜 2024-07-21 11:25:57

如果您的代码挂起,则意味着您的 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.

情绪少女 2024-07-21 11:25:57

快速浏览一下文档,如果您这样做了...

while (inStream.available() > 0 && (c = inStream.read()) != -1)

它似乎会在您实际阅读之前仔细检查您是否可以无阻塞地阅读。 不过我对此并不确定。

Just from a quick look at the docs, if you did...

while (inStream.available() > 0 && (c = inStream.read()) != -1)

It seems like it would double check that you can read without blocking before you actually read. I'm not certain on this though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文