开发者

Fell into infinite loop while receiving file using datainputstream and bufferedinputstream

开发者 https://www.devze.com 2023-04-10 13:05 出处:网络
I开发者_C百科 am trying to build a server program that receives file from client using DataInputStream and BufferedInputStream.

I开发者_C百科 am trying to build a server program that receives file from client using DataInputStream and BufferedInputStream.

Here's my code and it falls into infinite loop, I think it's because of not using available() but I am not really sure.

DataInputStream din = new DataInputStream(new BufferedInputStream(s.getInputStream()));
//s is socket that connects fine
fos = new FileOutputStream(directory+"/"+filename);

byte b[] = new byte[512]; 
int readByte = din.read(b);
while(readByte != 1){
    fos.write(b);
    readByte = din.read(b);
    //System.out.println("infinite loop...");
}

Can anyone tell me why it falls into infinite loop? if it is because of not using available , would you please tell me how to use it? I actually googled, but I was confused with the usage. Thank you very much


I think you want to do while(readByte != -1). See the documentation (-1 means there is nothing more to read).

Response to Comment

This works for me:

FileInputStream in = new FileInputStream(new File("C:\\Users\\Rachel\\Desktop\\Test.txt"));
DataInputStream din = new DataInputStream(new BufferedInputStream(in));
FileOutputStream fos = new FileOutputStream("C:\\Users\\Rachel\\Desktop\\MyOtherFile.txt");

byte b[] = new byte[512]; 
while(din.read(b) != -1){
    fos.write(b);
}

System.out.println("Got out");


As Rachel pointed out, the read method on DataInputStream returns the number of bytes successfully read in, or -1 if the end has been reached. The idiomatic way to loop until the end has been reached is while(readByte != -1) whereas you had 1 by mistake. If it is never the case that exactly 1 byte is read then this will be an infinite loop (readByte will never change from -1 once the end of the stream has been reached). If by chance there is an iteration where exactly 1 byte is read, this would have actually terminated early instead of going into an infinite loop.


Your question has already been answered but this code has another problem which is corrected below. The canonical stream copy loop looks like this:

while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号