Sftp (JSch wrapper) in Java

SftpService.java


import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SftpService {
    private static final String SFTP_ERRMSG_NO_SUCH_FILE = "No such file"; //Is it environment-dependent?
    private Session session = null;
    private ChannelSftp channelSftp = null;

    public SftpService(String host, int port, String username, String password) throws Exception {
        log.info("Connect(host={}, port={}, user={})", host, port, username);
        session = (new JSch()).getSession(username, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
    }

    public void cd(String path) throws Exception {
        log.info("{}Change to the directory.", path);
        channelSftp.cd(path);
    }

    public List<String> ls(String path) throws Exception {
        @SuppressWarnings({ "unchecked" })
        Vector<LsEntry> lsEntries = channelSftp.ls(path);
        List<String> filenames = new ArrayList<>();
        for (LsEntry lsEntry : lsEntries) {
            filenames.add(lsEntry.getFilename());
        }
        return filenames;
    }

    public InputStream get(String path) throws Exception {
        log.info("{}To get.", path);
        return channelSftp.get(path);
    }

    public void put(String localPath, String remotePath) throws Exception {
        log.info("{}To{}Put to", localPath, remotePath);
        channelSftp.put(localPath, remotePath);
    }

    public void mkdir(String path) throws Exception {
        log.info("{}Create a directory.", path);
        channelSftp.mkdir(path);
    }

    public void rmdir(String path) throws Exception {
        log.info("{}Delete the directory.", path);
        channelSftp.rmdir(path);
    }

    public void mkdirIfNotExists(String path) throws Exception {
        if (!isExists(path)) {
            mkdir(path);
        }
    }

    public void rmdirIfExists(String path) throws Exception {
        if (isExists(path)) {
            rmdir(path);
        }
    }

    public boolean isExists(String path) throws Exception {
        try {
            channelSftp.ls(path);
        } catch (SftpException e) {
            if (SFTP_ERRMSG_NO_SUCH_FILE.equals(e.getMessage())) {
                return false;
            } else {
                throw e;
            }
        }
        return true;
    }

    public void rename(String fromPath, String toPath) throws Exception {
        log.info("{}To{}Rename to.", fromPath, toPath);
        channelSftp.rename(fromPath, toPath);
    }

    public void disconnect() {
        if (channelSftp != null || session != null) {
            log.info("Disconnect");
        }
        if (channelSftp != null && channelSftp.isConnected()) {
            channelSftp.disconnect();
        }
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
        channelSftp = null;
        session = null;
    }
}

XXX.java


        SftpService sftpService = null;
        try {
            sftpService = new SftpService(host, port, username, password);
            sftpService.cd(targetDir);
            List<String> filenames = sftpService.ls("*.csv");
            for (String filename : filenames) {
                try (InputStream inputStream = sftpService.get(filename)) {
                    // do something
                }
            }
        } finally {
            if (sftpService != null) {
                sftpService.disconnect();
            }
        }

Recommended Posts

Sftp (JSch wrapper) in Java
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
Pi in Java
FizzBuzz in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Comments in Java source
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
[Java] Integer wrapper class reference
Read binary files in Java 1
Avoid Yubaba's error in Java
[Neta] Sleep Sort in Java
Edit ini in Java: ini4j
Java history in this world
Let Java segfault in 6 lines
Try calling JavaScript in Java
Try developing Spresense in Java (1)
I made roulette in Java.
Create hyperlinks in Java PowerPoint
Implement two-step verification in Java
Refactoring: Make Blackjack in Java
Write flyway callbacks in Java
Topic Analysis (LDA) in Java
Importing Excel data in Java 2
NEologd preprocessing in Java neologdn-java
Change java encoding in windows
Java Stream API in 5 minutes
Cannot find javax.annotation.Generated in Java 11
Implement Basic authentication in Java
Perl's grep-ish guy in Java