0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javaでsftp (JSchラッパ)

Last updated at Posted at 2020-08-14
pom.xml
		<dependency>
			<groupId>com.jcraft</groupId>
			<artifactId>jsch</artifactId>
			<version>0.1.55</version>
		</dependency>
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"; // 環境依存かも?
    private Session session = null;
    private ChannelSftp channelSftp = null;

    public SftpService(String host, int port, String username, String password) throws Exception {
        log.info("接続します。(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("{}ディレクトリに移動します。", 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("{}をgetします。", path);
        return channelSftp.get(path);
    }

    public void put(String localPath, String remotePath) throws Exception {
        log.info("{}を{}にputします。", localPath, remotePath);
        channelSftp.put(localPath, remotePath);
    }

    public void mkdir(String path) throws Exception {
        log.info("{}ディレクトリを作成します。", path);
        channelSftp.mkdir(path);
    }

    public void rmdir(String path) throws Exception {
        log.info("{}ディレクトリを削除します。", 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 void rm(String path) throws Exception {
        log.info("{}を削除します。", path);
        channelSftp.rm(path);
    }

    public void rmIfExists(String path) throws Exception {
        if (isExists(path)) {
            rm(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("{}を{}にリネームします。", fromPath, toPath);
        channelSftp.rename(fromPath, toPath);
    }

    public void disconnect() {
        if (channelSftp != null || session != null) {
            log.info("切断します。");
        }
        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();
            }
        }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?