如何在 JSch 中使用正则表达式下载 SFTP 文件

How to download SFTP file by using regular expression in JSch

我在服务器上有很多文件,名称如下:

STMTPULL.160618_030020 
O48PRMBATCH_170618_070209 
O48PRMBATCH_160618_030106
STMTPOST.160618_030020

我想使用正则表达式来定位最新的 O48PRMBATCH*

现在我只能下载具有实际文件名的文件。现在还不够。

如何更改代码以实现此功能?谢谢。

这是我的代码(代码已经更新,工作正常):

public class DownloadFile {

    public SFTPChannel getSFTPChannel() {
        return new SFTPChannel();
    }

    public void downloadFile(String srcPath, String dstPath, String fileName) throws Exception {

        DownloadFile test = new DownloadFile();

        Map<String, String> sftpDetails = new HashMap<String, String>();
        // Set host, port, user name, password
        sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "172.16.1.180");
        sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "v01uc");
        sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "v01uc");
        sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "22");

        SFTPChannel channel = test.getSFTPChannel();
        ChannelSftp chSftp = channel.getChannel(sftpDetails, 60000);

        String src = srcPath + fileName;

        Vector<ChannelSftp.LsEntry> obj = chSftp.ls(src);
        ArrayList<ChannelSftp.LsEntry> iList = new ArrayList<ChannelSftp.LsEntry>();
        for (int i = 0; i < obj.size(); i++){
            iList.add(obj.get(i));
        }

        Collections.sort(iList);

        int index = obj.size() - 1;
        String sFile = srcPath + iList.get(index).getFilename();
        String dst = dstPath + iList.get(index).getFilename();
        OutputStream out = new FileOutputStream(dst);
        try {
            chSftp.get(sFile, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            chSftp.quit();
            channel.closeChannel();
        }
    }
}

JSch中没有下载匹配正则表达式的文件的功能。

你必须自己编码。

  • 使用 ChannelSftp.ls 检索文件列表;
  • 迭代列表,查找与正则表达式匹配的文件;
  • 逐一下载匹配的文件。