November 2, 2015

Copy Files between Linux & Windows using Java

Maven Dependency

print 'hello w<!-- www.jcraft.com/jsch/ -->
<dependency>
 <groupId>com.jcraft</groupId>
 <artifactId>jsch</artifactId>
 <version>0.1.53</version>
</dependency>orld!'

FileCopierOverNetwork example class

package sawalha.poc.sch.trans;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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;
import com.jcraft.jsch.SftpProgressMonitor;

public class FileCopierOverNetwork {

    static Logger log = LogManager.getLogger(FileCopierOverNetwork.class.getName());

    final static SftpProgressMonitor monitor = new SftpProgressMonitor() {
        public void init(final int op, final String source, final String target, final long max) {
            log.info("sftp start uploading file from:" + source + " to:" + target);
        }

        public boolean count(final long count) {
            log.debug("sftp sending bytes: " + count);
            return true;
        }

        public void end() {
            log.info("sftp uploading is done.");
        }
    };

    public static void main(String args[]) {
        String hostname = "10.100.102.37";
        String username = "thin";
        String password = "thin123";
        String copyWinFrom = createTestFile("fromWindows.del").getAbsolutePath();
        // String copyWinFrom = "d:/fromWindows.del";
        String copyWinTo = "/home/thin/ibrahim-scripts/fromWindows.del";

        String copyLinuxFrom = "/home/thin/ibrahim-scripts/fromLinux.del";
        String copyLinuxTo = "fromLinux.del";

        try {
            putFile(hostname, username, password, copyWinFrom, copyWinTo);
            getFile(hostname, username, password, copyLinuxFrom, copyLinuxTo);
        } catch (JSchException e1) {
            e1.printStackTrace();
        } catch (SftpException e1) {
            e1.printStackTrace();
        }
        log.info("Done !!");
    }

    public static void putFile(String hostname, String username, String password, String copyFrom, String copyTo)
            throws JSchException, SftpException {
        log.info("Initiate sending file to Linux Server...");
        JSch jsch = new JSch();
        Session session = null;
        log.info("Trying to connect.....");
        session = jsch.getSession(username, hostname, 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        log.info("is server connected? " + session.isConnected());

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        log.info("Server's home directory: " + sftpChannel.getHome());
        try {
            sftpChannel.put(copyFrom, copyTo, monitor, ChannelSftp.OVERWRITE);
        } catch (SftpException e) {
            log.error("file was not found: " + copyFrom);
        }

        sftpChannel.exit();
        session.disconnect();
        log.info("Finished sending file to Linux Server...");
    }

    public static void getFile(String hostname, String username, String password, String copyFrom, String copyTo)
            throws JSchException {
        log.info("Initiate getting file from Linux Server...");
        JSch jsch = new JSch();
        Session session = null;
        log.info("Trying to connect.....");
        session = jsch.getSession(username, hostname, 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        log.info("is server connected? " + session.isConnected());

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        try {
            log.info(sftpChannel.getHome());
        } catch (SftpException e1) {
            e1.printStackTrace();
        }
        try {
            sftpChannel.get(copyFrom, copyTo, monitor, ChannelSftp.OVERWRITE);
        } catch (SftpException e) {
            log.error("file was not found: " + copyFrom);
        }

        sftpChannel.exit();
        session.disconnect();
        log.info("Finished getting file from Linux Server...");
    }

    public static File createTestFile(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            return file;
        }
        try {
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("This is ");
            fileWriter.write("a test");
            fileWriter.write("\n");
            fileWriter.write("Ibrahim Sawalha.");
            fileWriter.flush();
            fileWriter.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

No comments: