Java code to copy files from one linux machine to another linux machine

You can use this code snippet to copy files to another linux machine.

JSch jsch = new JSch();
Session session = null;
session = jsch.getSession("username","hostname",22);
session.setPassword("password");
session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
ChannelSftp channel = null;
channel = (ChannelSftp)session.openChannel("sftp");
channel.connect();
    File localFile = new File("localfilepath");
    //If you want you can change the directory using the following line.
    channel.cd(RemoteDirectoryPath)
channel.put(new FileInputStream(localFile),localFile.getName());
    channel.disconnect();
session.disconnect();

with that I have added my public key to remote system,generated using ssh-keygen.So it won't ask for password every time you run the program.


Copying a file from one host to another requires a daemon on the remote host, implementing some application-level file transmission protocol. This is a requirement no matter from which language you are going to talk to that remote daemon.

Your options for Linux systems are:

  • SSH. This requires a SSH daemon (say openssh-server) on the remote side. Because ssh is designed for security you will have to configure the remote host to authenticate you with either a password or a private key. Actually copying the file can be done via the scp utility or ssh client library (jsch would be an example of such).
  • NFS. The remote host installs a daemon (for example samba) and shares some files. Your local computer (cifs-utils package is capable of that) can then mount a remote location on the local file system. This way you can copy a file to the remote host by just copying the file locally. Authentication is optional, files are sent in plain over the network.
  • FTP. An ftp server is installed on remote side and configured to permit access to certain locations for certain users. You can then use any ftp client or some ftp client library (commons-net library from the Apache project, for instance) to connect to the remote ftp server and copy the files. Authentication is optional, files are sent in plain over the network.

All of this seems like a lot of work, and in deed it is, because there is not a single widely-adopted and standardized protocol that would be implemented and configured out-of-the-box on most systems.