简体   繁体   中英

Infinite loop reading Java inputstream

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

xfis.avialable() is returning 0 . When you try to read into a zero-length buffer, you always succeed and get a read length of 0 , not -1 . Buffer sizes should be independent of how many bytes are available. You use the value returned by xfis.read to determine how much of the buffer was filled.

Try this:

byte[] buffer = new byte[Math.max(1, size)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM