Java使用jsch远程下载文件

在windows环境连接linux环境进行远程下载文件。下面是选用jsch组件进行的实现。

JSch(Java Secure
Channel)是一个ssh2的java实现,允许连接到一个ssh服务器(即典型的xshell连接方式),并且可以使用端口转发,文件传输等。使用SFTP协议。
SFTP(Secure File Transfer Protocol)安全文件传送协议,可以为传输文件提供一种安全的加密方法。SFTP 为
SSH的一部份,是一种传输文件到服务器的安全方式,但是传输效率比普通的FTP要低。

public class SftpUtils {

    private static final Logger log = LoggerFactory.getLogger(SftpUtils.class);

    private String host;
    private String username;
    private String password;
    private int port = 22;
    private int timeOut = 6000;
    private ChannelSftp channelSftp = null;
    private Session sshSession = null;

    public SftpUtils(String host, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
    }

    /**
     * 通过SFTP连接服务器
     */
    public void connect() {
        try {
            JSch jsch = new JSch();
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.setTimeout(timeOut);
            sshSession.connect();

            channelSftp = (ChannelSftp) sshSession.openChannel("sftp");
            channelSftp.connect();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        if (this.channelSftp != null) {
            if (this.channelSftp.isConnected()) {
                this.channelSftp.disconnect();
            }
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
            }
        }
    }

    /**
     * 批量下载文件
     * @param remotePath:远程下载目录
     * @param localPath:本地保存目录
     * @return
     */
    public List<String> batchDownLoadFile(String remotePath, String localPath) {
        return batchDownLoadFile(remotePath, localPath, null, null, false);
    }

    /**
     * 批量下载文件
     * @param remotePath:远程下载目录
     * @param localPath:本地保存目录
     * @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
     * @param fileEndFormat:下载文件格式(文件格式,为空不做检验)
     * @param del:下载后是否删除sftp文件
     * @return
     */
    public List<String> batchDownLoadFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) {
        List<String> filenames = new ArrayList<>();
        try {
            Vector<?> vector = listFiles(remotePath);
            if (vector.size() > 0) {
                //size()中包含(. 和 ..)所以实际文件数目=size-2
                log.info("本次处理文件个数不为零,开始下载...fileSize={}", vector.size()-2);
                Iterator<?> it = vector.iterator();
                while (it.hasNext()) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                    String filename = entry.getFilename();
                    SftpATTRS attrs = entry.getAttrs();
                    if(".".equals(filename) || "..".equals(filename)) {
                        continue;
                    }

                    if (!attrs.isDir()) {
                        boolean flag;
                        String localFileName = localPath + filename;
                        fileFormat = fileFormat == null ? "" : fileFormat.trim();
                        fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim();
                        // 四种情况
                        if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
                            if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
                                flag = downloadFile(remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        deleteSFTP(remotePath, filename);
                                    }
                                }
                            }
                        } else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
                            if (filename.startsWith(fileFormat)) {
                                flag = downloadFile(remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        deleteSFTP(remotePath, filename);
                                    }
                                }
                            }
                        } else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
                            if (filename.endsWith(fileEndFormat)) {
                                flag = downloadFile(remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        deleteSFTP(remotePath, filename);
                                    }
                                }
                            }
                        } else {
                            flag = downloadFile(remotePath, filename, localPath, filename);
                            if (flag) {
                                filenames.add(localFileName);
                                if (flag && del) {
                                    deleteSFTP(remotePath, filename);
                                }
                            }
                        }
                    }else {
                        String newRemotePath = remotePath+ filename+ "/";
                        String newLocalPath = localPath+ filename+ "\\";
                        File fi = new File(newLocalPath);
                        if(!fi.exists()) {
                            fi.mkdirs();
                        }
                        batchDownLoadFile(newRemotePath, newLocalPath);
                    }
                }
            }
        } catch (SftpException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
        }
        return filenames;
    }

    /**
     * 下载单个文件
     * @param remotePath:远程下载目录
     * @param remoteFileName:下载文件名
     * @param localPath:本地保存目录
     * @param localFileName:保存文件名
     * @return
     */
    public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        FileOutputStream fileOutput = null;
        try {
            File file = new File(localPath + localFileName);
            File path = new File(localPath);
            if(!path.exists()) {
                path.mkdirs();
            }
            fileOutput = new FileOutputStream(file);
            channelSftp.get(remotePath + remoteFileName, fileOutput);
            System.out.println(remotePath + remoteFileName + "下载完成");
            return true;
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } catch (SftpException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            if (null != fileOutput) {
                try {
                    fileOutput.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 上传单个文件
     * @param remotePath:远程保存目录
     * @param remoteFileName:保存文件名
     * @param localPath:本地上传目录(以路径符号结束)
     * @param localFileName:上传的文件名
     * @return
     */
    public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        FileInputStream in = null;
        try {
            createDir(remotePath);
            File file = new File(localPath + localFileName);
            in = new FileInputStream(file);
            channelSftp.put(in, remoteFileName);
            return true;
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } catch (SftpException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 批量上传文件
     * @param remotePath:远程保存目录
     * @param localPath:本地上传目录(以路径符号结束)
     * @param del:上传后是否删除本地文件
     * @return
     */
    public boolean batchUploadFile(String remotePath, String localPath, boolean del) {
        try {
            File file = new File(localPath);
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile() && files[i].getName().indexOf("bak") == -1) {
                    if (this.uploadFile(remotePath, files[i].getName(), localPath, files[i].getName()) && del) {
                        deleteFile(localPath + files[i].getName());
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            this.disconnect();
        }
        return false;
    }

    /**
     * 删除本地文件
     * @param filePath
     * @return
     */
    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }
        if (!file.isFile()) {
            return false;
        }
        boolean rs = file.delete();
        return rs;
    }

    /**
     * 创建目录
     * @param createPath
     * @return
     */
    public boolean createDir(String createPath) {
        try {
            if (isDirExist(createPath)) {
                this.channelSftp.cd(createPath);
                return true;
            }
            String pathArry[] = createPath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString())) {
                    channelSftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    channelSftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    channelSftp.cd(filePath.toString());
                }

            }
            this.channelSftp.cd(createPath);
            return true;
        } catch (SftpException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断目录是否存在
     * @param directory
     * @return
     */
    public boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = channelSftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            log.error(e.getMessage());
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     * 删除stfp文件
     * @param directory:要删除文件所在目录
     * @param deleteFile:要删除的文件
     */
    public void deleteSFTP(String directory, String deleteFile) {
        try {
            channelSftp.rm(directory + deleteFile);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 列出目录下的文件
     * @param directory:要列出的目录
     * @return
     * @throws SftpException
     */
    public Vector<?> listFiles(String directory) throws SftpException {
        return channelSftp.ls(directory);
    }

    public static void main(String[] args) {
        SftpUtils sftpUtils = null;
        try {
            sftpUtils = new SftpUtils("192.168.1.1", "root", "root");
            sftpUtils.connect();
            sftpUtils.downloadFile("/opt/","1.pdf","D:\\","1.pdf");
            sftpUtils.batchDownLoadFile("/opt/", "D:\\11\\", "2021", null, false);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            sftpUtils.disconnect();
        }
    }

}
```java
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值