Wednesday, October 22, 2014

JSch: Transfer file between remote and local computers/machines/systems in Java

There are many ways to do this. One way is use JSch to open a SftpChannel between your local machine and remote machine. You can download JSch from its offical site: http://www.jcraft.com/jsch/

Following is an example of the code.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class RemoteSftp {
    public static void main(String[] args){
        try{
            JSch jsch=new JSch();

            Session session = jsch.getSession("<username>","<host name or IP address>");
            session.setPassword("<password>");
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp)channel;
       
            sftpChannel.get("<source file path/file name>", "<destination file path>");
            sftpChannel.put("<source file path/file name>", "<destination file path>");

            sftpChannel.disconnect();
            session.disconnect();
        }catch(JSchException e){
            e.printStackTrace();
        }catch(SftpException se){
            se.printStackTrace();
        }
    }
}

------------------------------------------------------------------------------------------------------------------
    
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment