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"; //Ist es umweltabhängig?
    private Session session = null;
    private ChannelSftp channelSftp = null;

    public SftpService(String host, int port, String username, String password) throws Exception {
        log.info("Verbinden(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("{}Wechseln Sie in das Verzeichnis.", 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("{}Bekommen.", path);
        return channelSftp.get(path);
    }

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

    public void mkdir(String path) throws Exception {
        log.info("{}Erstellen Sie ein Verzeichnis.", path);
        channelSftp.mkdir(path);
    }

    public void rmdir(String path) throws Exception {
        log.info("{}Löschen Sie das Verzeichnis.", 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("{}Zu{}Umbenennen in.", fromPath, toPath);
        channelSftp.rename(fromPath, toPath);
    }

    public void disconnect() {
        if (channelSftp != null || session != null) {
            log.info("Trennen");
        }
        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
Partisierung in Java
Änderungen in Java 11
Janken in Java
Umfangsrate in Java
FizzBuzz in Java
Lesen Sie JSON in Java
Interpreter-Implementierung durch Java
Janken App in Java
Einschränkungsprogrammierung in Java
Setzen Sie Java8 in Centos7
NVL-artiger Typ in Java
Verbinden Sie Arrays in Java
"Hallo Welt" in Java
Aufrufbare Schnittstelle in Java
Kommentare in der Java-Quelle
Formatieren Sie XML in Java
Einfache HTML-Spezialchars in Java
Boyer-Moore-Implementierung in Java
Hallo Welt in Java
Verwenden Sie OpenCV mit Java
WebApi-Memorandum mit Java
Typbestimmung in Java
Befehle in Java ausführen (Ping)
Verschiedene Threads in Java
Implementierung der Heap-Sortierung (in Java)
Zabbix API in Java
ASCII-Kunst in Java
Listen in Java vergleichen
POST JSON in Java
Fehler in Java ausdrücken
Erstellen Sie JSON in Java
Datumsmanipulation in Java 8
Was ist neu in Java 8?
Verwenden Sie PreparedStatement in Java
Was ist neu in Java 9,10,11
Parallele Ausführung in Java
[Java] Integer-Wrapper-Klassenreferenz
Lesen Sie Binärdateien in Java 1
Vermeiden Sie den Fehler, den Yuma in Java gemacht hat
[Neta] Sleep Sort in Java
Bearbeiten von ini in Java: ini4j
Java-Geschichte in dieser Welt
Segfo Java in 6 Zeilen
Versuchen Sie, JavaScript in Java aufzurufen
Lassen Sie uns Spresense mit Java entwickeln (1)
Ich habe ein Roulette in Java gemacht.
Implementierung der zweistufigen Authentifizierung in Java
Refactoring: Machen Sie Blackjack in Java
Schreiben Sie Flyway-Rückrufe in Java
Themenanalyse (LDA) in Java
Importieren Sie Excel-Daten mit Java 2
NEologd-Vorverarbeitung in Java neologdn-java
Ändern Sie die Java-Codierung in Windows
Java Stream API in 5 Minuten
Problem beim Finden von javax.annotation.Generated in Java 11 nicht
Implementieren Sie die Standardauthentifizierung in Java
Perls grep-ish Typ in Java