Question

I am trying to receive a file that client sends using DataInputStream and write it into file.

(Client sends the file using DataInputStream write(byte[], len, off) method)

Here's how I am trying to do, but it does not receive full data.

InputStream in = s.getInputStream(); //s is Socket that is connected.
BufferedInputStream bis = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bis);

FileOutputStream fos = new FileOutputStream(directory+"/"+filename);

byte b = din.readByte();
while(b != -1){
fos.write(b);
b = din.readByte();
}

I know that the implementation above may not be elegant.

but I am really new to java so please forbear with me about bad style

(I really appreciate if you recommend better one if you know)

the result file is only 4KB whereas it should be 401KB

How should I fix this code so I can have my code working?

THank you very much.

Was it helpful?

Solution

you are reading a byte, and -1 (cast to a byte) is a valid byte value. you don't want to stop on -1, but should instead catch EOFException.

you test for -1 when using one of the standard InputStream.read() methods (which return int, not byte).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top