无限循环读取Java输入流
我有一个关于java的InputStream的问题。
我正在从如下文件中读取数据:
FileInputStream xfis = new FileInputStream('filename')
int size = xfis.avaliable();
int len = 0 ;
byte[] buffer new byte[size];
while( (len = xfis.read(buffer) > -1 )
(
// process some logic
)
xfis.close();
....
并且每分钟运行一个批处理程序:
FileOutputStream fos = new FileOutputStream('filename')
FileLock flock = fos.getChannel().tryLock();
if(flock != null){
fos.write()
flock.release();
}
fos.close();
...
当两个程序同时读写时,读取文件的程序会陷入无限循环。
我该如何解决这个问题?
谢谢
I have a question about java's InputStream.
I am reading data from a file like below:
FileInputStream xfis = new FileInputStream('filename')
int size = xfis.avaliable();
int len = 0 ;
byte[] buffer new byte[size];
while( (len = xfis.read(buffer) > -1 )
(
// process some logic
)
xfis.close();
....
And also running a batch program every minute:
FileOutputStream fos = new FileOutputStream('filename')
FileLock flock = fos.getChannel().tryLock();
if(flock != null){
fos.write()
flock.release();
}
fos.close();
...
When both programs read and write at the same time the program that reads the file gets stuck in an infinite loop.
How can I solve that problem?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
xfis.avialable()
返回0
。当您尝试读取零长度缓冲区时,您总是会成功并获得读取长度0
,而不是-1
。缓冲区大小应与可用字节数无关。您可以使用 xfis.read 返回的值来确定缓冲区的填充量。试试这个:
xfis.avialable()
is returning0
. When you try to read into a zero-length buffer, you always succeed and get a read length of0
, not-1
. Buffer sizes should be independent of how many bytes are available. You use the value returned byxfis.read
to determine how much of the buffer was filled.Try this: