Java – How to transfer files from one computer to another over the network using Java


I need a simple application, preferably a cross-platform one, that enables sending of files between two computers.

It just need to accept and send the files, and show a progress bar. What applications could I use or how could I write one?

Best Solution

Sending and Receiving Files

The sending and receiving of a file basically breaks down to two simple pieces of code.

Recieving code:

ServerSocket serverSoc = new ServerSocket(LISTENING_PORT);

Socket connection = serverSoc.accept();

// code to read from connection.getInputStream();

Sending code:

File fileToSend;
InputStream fileStream = new BufferedInputStream(fileToSend);

Socket connection = new Socket(CONNECTION_ADDRESS, LISTENING_PORT);
OutputStream out = connection.getOutputStream();

// my method to move data from the file inputstream to the output stream of the socket
copyStream(fileStream, out);

The sending piece of code will be ran on the computer that is sending the code when they want to send a file.

The receiving code needs to be put inside a loop, so that everytime someone wants to connect to the server, the server can handle the request and then go back to waiting on serverSoc.accept().

To allow sending files between both computers, each computer will need to run the server (receiving code) to listen for incoming files, and they will both need to run the sending code when they want to send a file.

Progress Bar

The JProgressBar in Swing is easy enough to use. However, getting it to work properly and show current progress of the file transfer is slightly more difficult.

To get a progress bar to show up on a form only involves dropping it onto a JFrame and perhaps setting setIndeterminate(false) so hat it shows that your program is working.

To implement a progress bar correctly you will need to create your own implementation of a SwingWorker. The Java tutorials have a good example of this in theirlesson in concurrency.

This is a fairly difficult issue on its's own though. I would recommend asking this in it's own question if you need more help with it.