Question

I 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

Was it helpful?

Solution

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");

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top