ファイルシステムの-JAVA Sftpリモート操作:


JAvaリモート操作ファイルサーバ(linux)、sftpプロトコルを使用
バージョンは更新され続け、
現在のバージョン:0.31
バージョン更新時間:2016-10-13
バージョン修正の説明:
1.接続のクローズを修正し、クローズの方法をプライベートに変更し、使用者が自分でクローズすることを許可しない(そうでないと接続プールの取得エラーになる)
2.ファイルおよびフォルダの削除を最適化し、ファイルまたはフォルダが存在するかどうかを判断してから削除する
前言:
sftpはSecure File Transfer Protocolの略で、セキュリティファイル転送プロトコルです.ファイルの転送に安全な暗号化方法を提供できます.sftpはftpとほぼ同じ文法と機能を持っている.SFTPはSSHの一部であり、Bloggerサーバにファイルを転送するセキュリティ方式である.SSHパッケージには、SFTP(Secure File Transfer Protocol)というセキュリティファイル転送サブシステムが含まれており、SFTP自体には個別のデーモンプロセスはありません.sshdデーモンプロセスを使用する必要があります(ポート番号デフォルトは22)は、対応する接続操作を行うため、ある意味では、SFTPはサーバプログラムではなくクライアントプログラムのようなものである.SFTPは、同じく暗号化された伝送認証情報と伝送されたデータを用いているため、SFTPを用いることは非常時で安全である.ただし、この伝送方式では暗号化/復号技術が用いられるため、伝送効率は向上する通常のFTPよりもはるかに低いレートで、ネットワークセキュリティの要件が高い場合は、FTPの代わりにSFTPを使用できます.
このツールはJsch-Java Secure Channelのパッケージに基づいており、linuxサーバはプラグインやソフトウェアをインストールする必要はありません.
使用マニュアル:
まずはjarパッケージ

  com.jcraft
  jsch
  0.1.42

Sftpプロトコルツールクラス-v 0.1
package com.noryar.filesystem.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;

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;

/**
 *      .
 * @author Leon Lee
 */
public class SftpUtil {

    /**
     *       . /ddit-remote
     */
    private static final String PRE_FIX = "/test-noryar";

    /**
     *   sftp    .
     * @param host    
     * @param port   
     * @param username    
     * @param password   
     * @return     
     * @throws JSchException   
     */
    public static ChannelSftp getSftpConnect(final String host, final int port, final String username,
            final String password) throws JSchException {
        ChannelSftp sftp = null;
        JSch jsch = new JSch();
        jsch.getSession(username, host, port);
        Session sshSession = jsch.getSession(username, host, port);
        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        sftp = (ChannelSftp) channel;
        return sftp;
    }

    /**
     *     -sftp  .
     * @param downloadFile      
     * @param saveFile        
     * @param sftp sftp  
     * @return   
     * @throws Exception   
     */
    public static File download(final String downloadFile, final String saveFile, final ChannelSftp sftp)
            throws Exception {
        FileOutputStream os = null;
        File file = new File(saveFile);
        try {
            if (!file.exists()) {
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                file.createNewFile();
            }
            os = new FileOutputStream(file);
            List list = formatPath(downloadFile);
            sftp.get(list.get(0) + list.get(1), os);
        } catch (Exception e) {
            exit(sftp);
            throw e;
        } finally {
            os.close();
        }
        return file;
    }

    /**
     *     -sftp  .
     * @param downloadFile      
     * @param saveFile        
     * @param sftp sftp  
     * @return    byte[]
     * @throws Exception   
     */
    public static byte[] downloadAsByte(final String downloadFile, final ChannelSftp sftp) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            List list = formatPath(downloadFile);
            sftp.get(list.get(0) + list.get(1), os);
        } catch (Exception e) {
            exit(sftp);
            throw e;
        } finally {
            os.close();
        }
        return os.toByteArray();
    }

    /**
     *     -sftp  .
     * @param deleteFile       
     * @param sftp sftp  
     * @throws Exception   
     */
    public static void rmFile(final String deleteFile, final ChannelSftp sftp) throws Exception {
        try {
            sftp.rm(deleteFile);
        } catch (Exception e) {
            exit(sftp);
            throw e;
        }
    }

    /**
     *      -sftp  .
     * @param deleteFile      
     * @param sftp sftp  
     * @throws Exception   
     */
    public static void rmDir(final String pathString, final ChannelSftp sftp) throws Exception {
        try {
            sftp.rmdir(pathString);
        } catch (Exception e) {
            exit(sftp);
            throw e;
        }
    }

    /**
     *     -sftp  .
     * @param srcFile    
     * @param dir     
     * @param fileName      
     * @param sftp sftp  
     * @throws Exception   
     */
    private static void uploadFile(final String srcFile, final String dir, final String fileName, final ChannelSftp sftp)
            throws Exception {
        mkdir(dir, sftp);
        sftp.cd(dir);
        sftp.put(srcFile, fileName);
    }

    /**
     *     -sftp  .
     * @param srcFile      ,/xxx/xxx.zip   x:/xxx/xxx.zip;
     * @param sftp sftp  
     * @throws Exception   
     */
    public static void uploadFile(final String srcFile, final ChannelSftp sftp) throws Exception {
        try {
            File file = new File(srcFile);
            if (file.exists()) {
                List list = formatPath(srcFile);
                uploadFile(srcFile, list.get(0), list.get(1), sftp);
            }
        } catch (Exception e) {
            exit(sftp);
            throw e;
        }
    }

    /**
     *          .
     * @param dir        /xxx/xxx/xxx/        /
     * @param sftp sftp  
     * @throws Exception   
     */
    public static boolean mkdir(final String dir, final ChannelSftp sftp) throws Exception {
        try {
            if (StringUtils.isBlank(dir))
                return false;
            String md = dir.replaceAll("\\\\", "/");
            if (md.indexOf("/") != 0 || md.length() == 1)
                return false;
            return mkdirs(md, sftp);
        } catch (Exception e) {
            exit(sftp);
            throw e;
        }
    }

    /**
     *        .
     * @param dir   
     * @param sftp sftp  
     * @return       
     * @throws SftpException   
     */
    private static boolean mkdirs(final String dir, final ChannelSftp sftp) throws SftpException {
        String dirs = dir.substring(1, dir.length() - 1);
        String[] dirArr = dirs.split("/");
        String base = "";
        for (String d : dirArr) {
            base += "/" + d;
            if (dirExist(base + "/", sftp)) {
                continue;
            } else {
                sftp.mkdir(base + "/");
            }
        }
        return true;
    }

    /**
     *          .
     * @param dir      , /xxx/xxx/
     * @param sftp sftp  
     * @return     
     */
    public static boolean dirExist(final String dir, final ChannelSftp sftp) {
        try {
            Vector> vector = sftp.ls(dir);
            if (null == vector)
                return false;
            else
                return true;
        } catch (SftpException e) {
            return false;
        }
    }

    /**
     *      .
     * @param srcPath    . /xxx/xxx/xxx.yyy   X:/xxx/xxx/xxx.yy
     * @return list,       (/xxx/xxx/),       (xxx.yy)
     */
    public static List formatPath(final String srcPath) {
        List list = new ArrayList(2);
        String dir = "";
        String fileName = "";
        String repSrc = srcPath.replaceAll("\\\\", "/");
        int firstP = repSrc.indexOf("/");
        int lastP = repSrc.lastIndexOf("/");
        fileName = repSrc.substring(lastP + 1);
        dir = repSrc.substring(firstP, lastP);
        dir = PRE_FIX + (dir.length() == 1 ? dir : (dir + "/"));
        list.add(dir);
        list.add(fileName);
        return list;
    }

    /**
     *     -sftp  .
     * @param sftp sftp  
     */
    public static void exit(final ChannelSftp sftp) {
        sftp.exit();
    }

    public static void main(String[] args) throws Exception {
        ChannelSftp sftp = getSftpConnect("192.168.0.35", 22, "root", "root");
        String pathString = "C:\\test\\aaa\\Foxmail7.zip";
        File file = new File(pathString);
        System.out.println("      ...");
        uploadFile(pathString, sftp);
        System.out.println("    ,        ...");
        file.delete();
        System.out.println("    ,        ...");
        if (!file.exists()) {
            System.out.println("     ,          ...");
            download(pathString, pathString, sftp);
            System.out.println("    ");
        } else {
            System.out.println("       ");
        }
        exit(sftp);
        System.exit(0);
    }
}

v0.2-sftp接続プールの追加
sftp接続を作成するコストがかかるため、同じホストの接続が接続プールに格納されていることを考慮し、次回sftp接続を取得するときに直接接続プールに行って取得します.
以下のコードはv 0を置換.バージョン1のgetSftpConnect()メソッドに、メンバー変数を追加すればよい
    /**
     * sftp   .
     */
    private static final Map SFTP_CHANNEL_POOL = new HashMap();

    /**
     *   sftp    .
     * @param host    
     * @param port   
     * @param username    
     * @param password   
     * @return     
     * @throws JSchException   
     */
    public static ChannelSftp getSftpConnect(final String host, final int port, final String username,
            final String password) throws JSchException {
        Session sshSession = null;
        Channel channel = null;
        ChannelSftp sftp = null;
        String key = host + "," + port + "," + username + "," + password;
        if (null == SFTP_CHANNEL_POOL.get(key)) {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            channel = sshSession.openChannel("sftp");
            channel.connect();
            SFTP_CHANNEL_POOL.put(key, channel);
        } else {
            channel = SFTP_CHANNEL_POOL.get(key);
            sshSession = channel.getSession();
            if (!sshSession.isConnected())
                sshSession.connect();
            if (!channel.isConnected())
                channel.connect();
        }
        sftp = (ChannelSftp) channel;
        return sftp;
    }

v0.3-バグを修正し、フォルダを再帰的に削除する機能を追加
package com.noryar.filesystem.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;

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

/**
 *      .
* 1. '/' ,
* 2. , sftp ( session channel), * @author Leon Lee */ public class SftpUtil { /** * . /ddit-remote */ private static final String PRE_FIX = "/test-noryar"; /** * sftp . */ private static final Map SFTP_CHANNEL_POOL = new HashMap(); /** * sftp . * @param host * @param port * @param username * @param password * @return * @throws JSchException */ public static ChannelSftp getSftpConnect(final String host, final int port, final String username, final String password) throws JSchException { Session sshSession = null; Channel channel = null; ChannelSftp sftp = null; String key = host + "," + port + "," + username + "," + password; if (null == SFTP_CHANNEL_POOL.get(key)) { JSch jsch = new JSch(); jsch.getSession(username, host, port); sshSession = jsch.getSession(username, host, port); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); channel = sshSession.openChannel("sftp"); channel.connect(); SFTP_CHANNEL_POOL.put(key, channel); } else { channel = SFTP_CHANNEL_POOL.get(key); sshSession = channel.getSession(); if (!sshSession.isConnected()) sshSession.connect(); if (!channel.isConnected()) channel.connect(); } sftp = (ChannelSftp) channel; return sftp; } /** * -sftp . * @param downloadFile * @param saveFile * @param sftp sftp * @return * @throws Exception */ public static File download(final String downloadFile, final String saveFile, final ChannelSftp sftp) throws Exception { FileOutputStream os = null; File file = new File(saveFile); try { if (!file.exists()) { File parentFile = file.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } file.createNewFile(); } os = new FileOutputStream(file); List list = formatPath(downloadFile); sftp.get(list.get(0) + list.get(1), os); } catch (Exception e) { exit(sftp); e.getMessage(); throw e; } finally { os.close(); } return file; } /** * -sftp . * @param downloadFile * @param saveFile * @param sftp sftp * @return byte[] * @throws Exception */ public static byte[] downloadAsByte(final String downloadFile, final ChannelSftp sftp) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { List list = formatPath(downloadFile); sftp.get(list.get(0) + list.get(1), os); } catch (Exception e) { exit(sftp); throw e; } finally { os.close(); } return os.toByteArray(); } /** * -sftp . * @param pathString * @param sftp sftp * @throws Exception */ public static void rmFile(final String pathString, final ChannelSftp sftp) throws Exception { try { List list = formatPath(pathString); sftp.rm(list.get(0) + list.get(1)); } catch (Exception e) { exit(sftp); throw e; } } /** * -sftp . , . * @param pathString * @param sftp sftp * @param resursion * @throws Exception */ public static void rmDir(final String pathString, final ChannelSftp sftp, final boolean recursion) throws Exception { try { String fp = formatPath(pathString).get(0); if (recursion) exeRmRec(fp, sftp); else sftp.rmdir(fp); } catch (Exception e) { exit(sftp); throw e; } } /** * . * @param pathString * @param sftp sftp * @throws SftpException */ private static void exeRmRec(final String pathString, final ChannelSftp sftp) throws SftpException { @SuppressWarnings("unchecked") Vector vector = sftp.ls(pathString); if (vector.size() == 1) { // , sftp.rm(pathString); } else if (vector.size() == 2) { // , sftp.rmdir(pathString); } else { String fileName = ""; // for (LsEntry en : vector) { fileName = en.getFilename(); if (".".equals(fileName) || "..".equals(fileName)) { continue; } else { exeRmRec(pathString + "/" + fileName, sftp); } } // sftp.rmdir(pathString); } } /** * -sftp . * @param srcFile * @param dir * @param fileName * @param sftp sftp * @throws Exception */ private static void uploadFile(final String srcFile, final String dir, final String fileName, final ChannelSftp sftp) throws Exception { mkdir(dir, sftp); sftp.cd(dir); sftp.put(srcFile, fileName); } /** * -sftp . * @param srcFile ,/xxx/xx.yy x:/xxx/xxx.yy * @param sftp sftp * @return * @throws Exception */ public static boolean uploadFile(final String srcFile, final ChannelSftp sftp) throws Exception { try { File file = new File(srcFile); if (file.exists()) { List list = formatPath(srcFile); uploadFile(srcFile, list.get(0), list.get(1), sftp); return true; } return false; } catch (Exception e) { exit(sftp); throw e; } } /** * . * @param dir /xxx/xxx/ / * @param sftp sftp * @throws Exception */ public static boolean mkdir(final String dir, final ChannelSftp sftp) throws Exception { try { if (StringUtils.isBlank(dir)) return false; String md = dir.replaceAll("\\\\", "/"); if (md.indexOf("/") != 0 || md.length() == 1) return false; return mkdirs(md, sftp); } catch (Exception e) { exit(sftp); throw e; } } /** * . * @param dir * @param sftp sftp * @return * @throws SftpException */ private static boolean mkdirs(final String dir, final ChannelSftp sftp) throws SftpException { String dirs = dir.substring(1, dir.length() - 1); String[] dirArr = dirs.split("/"); String base = ""; for (String d : dirArr) { base += "/" + d; if (dirExist(base + "/", sftp)) { continue; } else { sftp.mkdir(base + "/"); } } return true; } /** * . * @param dir , /xxx/xxx/ * @param sftp sftp * @return */ private static boolean dirExist(final String dir, final ChannelSftp sftp) { try { Vector> vector = sftp.ls(dir); if (null == vector) return false; else return true; } catch (SftpException e) { return false; } } /** * . * @param srcPath . /xxx/xxx/xxx.yyy X:/xxx/xxx/xxx.yy * @return list, (/xxx/xxx/), (xxx.yy) */ public static List formatPath(final String srcPath) { List list = new ArrayList(2); String repSrc = srcPath.replaceAll("\\\\", "/"); int firstP = repSrc.indexOf("/"); int lastP = repSrc.lastIndexOf("/"); String fileName = lastP + 1 == repSrc.length() ? "" : repSrc.substring(lastP + 1); String dir = firstP == -1 ? "" : repSrc.substring(firstP, lastP); dir = PRE_FIX + (dir.length() == 1 ? dir : (dir + "/")); list.add(dir); list.add(fileName); return list; } /** * -sftp . * @param sftp sftp */ public static void exit(final ChannelSftp sftp) { sftp.exit(); } public static void main(String[] args) throws Exception { ChannelSftp sftp = getSftpConnect("192.168.0.35", 22, "root", "root"); // String pathString = "C:\\test\\ccc\\Foxmail7.zip"; // File file = new File(pathString); // System.out.println(" ..."); // uploadFile(pathString, sftp); // System.out.println(" , ..."); // file.delete(); // System.out.println(" , ..."); // if (!file.exists()) { // System.out.println(" , ..."); // download(pathString, pathString, sftp); // System.out.println(" "); // } else { // System.out.println(" "); // } rmDir("", sftp, true); exit(sftp); System.exit(0); } }

v0.31
接続のクローズを修正し、クローズ方法をプライベートに変更し、ユーザーが自分でクローズすることは許可されません(そうでないと接続プールの取得エラーが発生します)
ファイルおよびフォルダの削除を最適化し、ファイルまたはフォルダが存在するかどうかを判断してから削除します.
package com.noryar.filesystem.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;

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

/**
 *      .
* 1. '/' ,
* 2. @since version-0.3 , sftp ( session channel)(del @ version 0.31),
* @author Leon Lee */ public class SftpUtil { /** * . /ddit-remote */ private static final String PRE_FIX = "/test-noryar"; /** * sftp . */ private static final Map SFTP_CHANNEL_POOL = new HashMap(); /** * sftp . * @param host * @param port * @param username * @param password * @return * @throws JSchException */ public static ChannelSftp getSftpConnect(final String host, final int port, final String username, final String password) throws JSchException { Session sshSession = null; Channel channel = null; ChannelSftp sftp = null; String key = host + "," + port + "," + username + "," + password; if (null == SFTP_CHANNEL_POOL.get(key)) { JSch jsch = new JSch(); jsch.getSession(username, host, port); sshSession = jsch.getSession(username, host, port); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); channel = sshSession.openChannel("sftp"); channel.connect(); SFTP_CHANNEL_POOL.put(key, channel); } else { channel = SFTP_CHANNEL_POOL.get(key); sshSession = channel.getSession(); if (!sshSession.isConnected()) sshSession.connect(); if (!channel.isConnected()) channel.connect(); } sftp = (ChannelSftp) channel; return sftp; } /** * -sftp . * @param downloadFile * @param saveFile * @param sftp sftp * @return * @throws Exception */ public static File download(final String downloadFile, final String saveFile, final ChannelSftp sftp) throws Exception { FileOutputStream os = null; File file = new File(saveFile); try { if (!file.exists()) { File parentFile = file.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } file.createNewFile(); } os = new FileOutputStream(file); List list = formatPath(downloadFile); sftp.get(list.get(0) + list.get(1), os); } catch (Exception e) { throw e; } finally { os.close(); } return file; } /** * -sftp . * @param downloadFile * @param saveFile * @param sftp sftp * @return byte[] * @throws Exception */ public static byte[] downloadAsByte(final String downloadFile, final ChannelSftp sftp) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { List list = formatPath(downloadFile); sftp.get(list.get(0) + list.get(1), os); } catch (Exception e) { throw e; } finally { os.close(); } return os.toByteArray(); } /** * -sftp . * @param pathString * @param sftp sftp * @throws SftpException */ public static void rmFile(final String pathString, final ChannelSftp sftp) throws SftpException { List list = formatPath(pathString); String dir = list.get(0); String file = list.get(1); if (dirExist(dir + file, sftp)) { sftp.rm(list.get(0) + list.get(1)); } } /** * -sftp . , . * @param pathString * @param sftp sftp * @param resursion * @throws SftpException */ public static void rmDir(final String pathString, final ChannelSftp sftp, final boolean recursion) throws SftpException { String fp = formatPath(pathString).get(0); if (dirExist(fp, sftp)) { if (recursion) exeRmRec(fp, sftp); else sftp.rmdir(fp); } } /** * . * @param pathString * @param sftp sftp * @throws SftpException */ private static void exeRmRec(final String pathString, final ChannelSftp sftp) throws SftpException { @SuppressWarnings("unchecked") Vector vector = sftp.ls(pathString); if (vector.size() == 1) { // , sftp.rm(pathString); } else if (vector.size() == 2) { // , sftp.rmdir(pathString); } else { String fileName = ""; // for (LsEntry en : vector) { fileName = en.getFilename(); if (".".equals(fileName) || "..".equals(fileName)) { continue; } else { exeRmRec(pathString + "/" + fileName, sftp); } } // sftp.rmdir(pathString); } } /** * -sftp . * @param srcFile * @param dir * @param fileName * @param sftp sftp * @throws Exception */ private static void uploadFile(final String srcFile, final String dir, final String fileName, final ChannelSftp sftp) throws SftpException { mkdir(dir, sftp); sftp.cd(dir); sftp.put(srcFile, fileName); } /** * -sftp . * @param srcFile ,/xxx/xx.yy x:/xxx/xxx.yy * @param sftp sftp * @return * @throws SftpException */ public static boolean uploadFile(final String srcFile, final ChannelSftp sftp) throws SftpException { File file = new File(srcFile); if (file.exists()) { List list = formatPath(srcFile); uploadFile(srcFile, list.get(0), list.get(1), sftp); return true; } return false; } /** * . * @param dir /xxx/xxx/ / * @param sftp sftp * @throws SftpException */ public static boolean mkdir(final String dir, final ChannelSftp sftp) throws SftpException { if (StringUtils.isBlank(dir)) return false; String md = dir.replaceAll("\\\\", "/"); if (md.indexOf("/") != 0 || md.length() == 1) return false; return mkdirs(md, sftp); } /** * . * @param dir * @param sftp sftp * @return * @throws SftpException */ private static boolean mkdirs(final String dir, final ChannelSftp sftp) throws SftpException { String dirs = dir.substring(1, dir.length() - 1); String[] dirArr = dirs.split("/"); String base = ""; for (String d : dirArr) { base += "/" + d; if (dirExist(base + "/", sftp)) { continue; } else { sftp.mkdir(base + "/"); } } return true; } /** * . * @param dir , /xxx/xxx/ * @param sftp sftp * @return */ private static boolean dirExist(final String dir, final ChannelSftp sftp) { try { Vector> vector = sftp.ls(dir); if (null == vector) return false; else return true; } catch (SftpException e) { return false; } } /** * . * @param srcPath . /xxx/xxx/xxx.yyy X:/xxx/xxx/xxx.yy * @return list, (/xxx/xxx/), (xxx.yy) */ public static List formatPath(final String srcPath) { List list = new ArrayList(2); String repSrc = srcPath.replaceAll("\\\\", "/"); int firstP = repSrc.indexOf("/"); int lastP = repSrc.lastIndexOf("/"); String fileName = lastP + 1 == repSrc.length() ? "" : repSrc.substring(lastP + 1); String dir = firstP == -1 ? "" : repSrc.substring(firstP, lastP); dir = PRE_FIX + (dir.length() == 1 ? dir : (dir + "/")); list.add(dir); list.add(fileName); return list; } /** * -sftp .( , ) * @param sftp sftp */ private static void exit(final ChannelSftp sftp) { sftp.exit(); } public static void main(String[] args) throws Exception { ChannelSftp sftp = getSftpConnect("192.168.0.35", 22, "root", "root"); // String pathString = "C:\\test\\ccc\\Foxmail7.zip"; // File file = new File(pathString); // System.out.println(" ..."); // uploadFile(pathString, sftp); // System.out.println(" , ..."); // file.delete(); // System.out.println(" , ..."); // if (!file.exists()) { // System.out.println(" , ..."); // download(pathString, pathString, sftp); // System.out.println(" "); // } else { // System.out.println(" "); // } // rmDir("", sftp, true); String path = "E:\\aaa.zip"; File file = SftpUtil.download(path, path, sftp); // SftpUtil.exit(sftp); exit(sftp); System.exit(0); } }