File transfer between two computer using java program ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

File transfer between two computer using java program ?

how to transfer the any file(.txt,.html,.pdf,.etc) from one computer to another computer using simple java networking program.

7th Jan 2017, 6:44 PM
Rahulsinh J. Parmar
Rahulsinh J. Parmar - avatar
1 Answer
0
You are reading the socket until read() returns -1. This is the end-of-stream condition (EOS). EOS happens when the peer closes the connection. Not when it finishes writing one file. You need to send the file size ahead of each file. You're already doing a similar thing with the file count. Then make sure you read exactly that many bytes for that file: String filename = dis.readUTF(); long fileSize = dis.readLong(); FileOutputStream fos = new FileOutputStream(filename); while (fileSize > 0 && (n = dis.read(buf, 0, (int)Math.min(buf.length, fileSize)) != -1) { fos.write(buf,0,n); fileSize -= n; } fos.close(); You can enclose all this in a loop that terminates when readUTF() throws EOFException. Conversely of course you have to call writeUTF(filename) and writeLong(filesize) at the sender, before sending the data.
8th Jan 2017, 7:18 PM
Ahmed El-Essawy
Ahmed El-Essawy - avatar