How would you send a file over a socket connection?

Brian O'Byrne

If both ends of the connection knew exactly what was happening or expected (e.g. a single file with a constant filename, in the simplest case), you could do something as simple as have one end read from a FileInputStream and write to the socket's OutputStream, while the other end reads from the socket's InputStream and writes to a FileOutputStream.

If you need to transfer multiple files, or need to transfer some details about the file other than the contents (for example, the file name and path), you could create a class which represents the file and serialize it out to the socket. At the simplest that might look like this:

import java.io.*;

public class TransferableFile implements Serializable
  private byte[] contents;
  private String fileName;

  public TransferableFile(String _fileName) {
    fileName = _fileName;
    // Open a FileInputStream and populate
    // the contents array

  public void writeFile() {
    // Open a FileOutputStream to write
    // the contents array

.. at one end you could create the TransferableFile and serialize it out to the socket. At the other end you deserialize and invoke writeFile().

An improvement on that would be to do the file I/O in the readObject() and writeObject() methods. That is, read the file from the disk in writeObject() and stream the data straight out to the socket, then write the data directly to the disk in readObject(). This would allow you to handle arbitrarily large files without changing the memory requirement.

If you need to do anything more complex than that, your best bet is to get an FTP client/server. A quick search in this Networking FAQ or in Google should list a few options.