sftp jsch文件移動備份的思路


1.jsch jar包不支持mv cp等移動復制的功能,轉換思路,sftp下載文件到本地服務器,目錄可以考慮使用/年/月/日層級。

2.然后sftp下載操作完畢,記錄一張文件操作表,記錄下載狀態。

3.在定時備份的任務中,根據文件操作表的下載狀態,循環操作:首先檢查本地是否該文件存在,存在則在sftp jsch rm刪除該文件。

4.最后將本地的文件批量上傳到sftp服務器需要轉移備份的新文件夾目錄上面實現。目錄可以考慮使用/年/月/日層級。

jsch支持一次mkdir一個目錄,而不允許一次創建多層級目錄。需要遍歷:

String[] folders = path.split( "/" );
for ( String folder : folders ) {
    if ( folder.length() > 0 ) {
        try {
            sftp.cd( folder );
        }
        catch ( SftpException e ) {
            sftp.mkdir( folder );
            sftp.cd( folder );
        }
    }
}

批量上傳(關鍵代碼)

private static ChannelSftp upload(String path, String dst, SftpProgressMonitor monitor) throws SftpException {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        ChannelSftp chSftp = null;
        try {
            chSftp = ChannelSftpSingleton.getInstance().getChannelSftp();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        if (chSftp == null) {
            return null;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length <= 0) {
                return null;
            }
            for (File f : files) {
                String fp = f.getAbsolutePath();
                if (f.isDirectory()) {
                    String mkdir = dst + "/" + f.getName();
                    try {
                        chSftp.cd(mkdir);
                    } catch (Exception e) {
                        chSftp.mkdir(mkdir);
                    }
                    upload(fp, mkdir, monitor);
                } else {
                    chSftp.put(fp, dst, monitor, ChannelSftp.OVERWRITE);
                }
            }
        } else {
            String fp = file.getAbsolutePath();
            chSftp.put(fp, dst, monitor, ChannelSftp.OVERWRITE);
        }
        return chSftp;
    }

測試類

String src = "本地文件夾目錄";
        String dst = "sftp文件夾目錄";
        try {
            uploadFilesToServer(src, dst, new SftpProgressMonitor() {
                @Override
                public void init(int i, String src, String dst, long size) {
                    System.out.println("正在上傳 " + src + " 到 " + dst + ",文件大小:" + (double) (size) + "b");
                }

                @Override
                public boolean count(long l) {
                    return true;
                }

                @Override
                public void end() {
                    System.out.println("上傳成功");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

最后需處理jsch的各種退出,各種關閉操作。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM