Android/Java - How check when the OutputStream has finished to write the bytes -
i have created server socket accept connection client, , when connection established image transferred using outputstream write bytes. question how can check if outputstream has finished write bytes before close socket connection, because not image correctly transferred. code i'm using:
file photofile = new file(getheader); //getheader file have transfer int size2 = (int) photofile.length(); byte[] bytes2 = new byte[size2]; try { bufferedinputstream buf = new bufferedinputstream(new fileinputstream(photofile)); buf.read(bytes2, 0, bytes2.length); buf.close(); } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } client.getoutputstream().write(bytes2, 0, size2); //client server socket
thanks
my question how can check if outputstream has finished write bytes before close socket connection, because not image correctly transferred
no, problem assuming read()
fills buffer. outputstream
has finished writing when write returns. memorize this:
while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); }
this correct way copy streams in java. yours isn't.
you assuming file size fits int,
, entire file fits memory, , wasting both time , space reading entire file (maybe) memory before writing anything. code above works size buffer 1 byte upwards. use 8192 bytes.
Comments
Post a Comment