This simple example demonstrates how to use Java to transfer files between the client and the server.
Server Source Code:
Import java.net. *; <br/> Import Java. io. *; <br/> public class fileserver {<br/> Public static void main (string [] ARGs) throwsioexception {<br/> // create socket <br/> serversocket servsock = new serversocket (13267); <br/> while (true) {<br/> system. out. println ("waiting... "); <br/> socket sock = servsock. accept (); <br/> system. out. println ("accepted connection:" + sock); <br/> // sendfile <br/> file myfile = new file ("source.pdf "); <br/> byte [] mybytearray = new byte [(INT) myfile. length ()]; <br/> fileinputstream FCM = new fileinputstream (myfile); <br/> bufferedinputstream Bis = new bufferedinputstream (FCM); <br/> bis. read (mybytearray, 0, mybytearray. length); <br/> outputstream OS = sock. getoutputstream (); <br/> system. out. println ("sending... "); <br/> OS. write (mybytearray, 0, mybytearray. length); <br/> OS. flush (); <br/> sock. close (); <br/>}< br/>}
Client source code:
Import java.net. *; <br/> Import Java. io. *; <br/> public class fileclient {<br/> Public static void main (string [] ARGs) throws ioexception {<br/> int filesize = 6022386; // filesize temporary hardcoded <br/> long start = system. currenttimemillis (); <br/> int bytesread; <br/> int current = 0; <br/> // localhost for testing <br/> socket sock = new socket ("127.0.0.1", 13267); <br/> system. out. println ("Connecting... "); </P> <p> // receive file <br/> byte [] mybytearray = new byte [filesize]; <br/> inputstream is = sock. getinputstream (); <br/> fileoutputstream Fos = new fileoutputstream ("source-copy.pdf"); <br/> bufferedoutputstream Bos = new bufferedoutputstream (FOS); <br/> bytesread = is. read (mybytearray, 0, mybytearray. length); <br/> current = bytesread; <br/> // thanks to. cádiz for the bug fix <br/> do {<br/> bytesread = <br/> is. read (mybytearray, current, (mybytearray. length-current); <br/> If (bytesread> = 0) Current + = bytesread; <br/>}while (bytesread>-1 ); </P> <p> Bos. write (mybytearray, 0, current); <br/> Bos. flush (); <br/> long end = system. currenttimemillis (); <br/> system. out. println (end-Start); <br/> Bos. close (); <br/> sock. close (); <br/>}< br/>}