【问题标题】:using matchpattern in sftp ls command在 sftp ls 命令中使用 matchpattern
【发布时间】:2014-07-11 22:57:55
【问题描述】:

我的 SFTP 服务器上有两个文件

xyz07012014abc.txt
xyz06072014abc.txt

我有一个具有如下匹配模式的 Java 程序:month="07" 和 year="2014"

matchPattern = "*" + month + "*" + year + "*";

上面的 matchpattern 让我得到了这两个文件。但是,我只想要以下文件:

xyz07012014abc.txt

如何修改我的匹配模式以获得正确的结果。

编辑

我正在使用以下 java 方法并将上面的 matchpattern 提供给它。

private void getFilesFromFTP(String sftpBase, String matchPattern) throws JSchException, SftpException{
    log.debug("Downloading reward files from FTP server...");
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    JSch jsch = new JSch();
    session = jsch.getSession(REWARDS_SFTP_USER, REWARDS_SFTP_SERVER, 22);
    session.setPassword(REWARDS_SFTP_PASSWORD);
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();

    channel = session.openChannel("sftp");
    channel.connect();
    channelSftp = (ChannelSftp) channel;
    channelSftp.cd(sftpBase);

    Vector<ChannelSftp.LsEntry> list = channelSftp.ls(matchPattern);
    for (ChannelSftp.LsEntry entry : list) {
        channelSftp.get(entry.getFilename(), TEMP_DIRECTORY_PATH + entry.getFilename());
    }

    channel.disconnect();
    session.disconnect();
}

【问题讨论】:

  • 您的 matchPattern 不是正确的正则表达式(第一个 * 前面没有任何内容)。提供一些正确的例子来解释你的问题,让我们重现它。
  • 这看起来不像一个正则表达式。特别是,在正则表达式中,* 匹配前一个字符/组的 0 个或多个。您编写的模式 ("*07*2014*) 不应与任一文件名匹配。
  • 它确实匹配两个文件名。
  • 那么这不是您要询问的正则表达式。 * 似乎是通配符,而不是量词。
  • Pshemo:好的。我没有意识到这一点。请随时根据您的意愿编辑标签。

标签: java ftp jsch


【解决方案1】:

以下是 Jsch JavaDoc 的链接:

http://epaul.github.io/jsch-documentation/simple.javadoc/com/jcraft/jsch/ChannelSftp.html#ls(java.lang.String)

上面写着:

ls

public Vector ls(String path)
          throws SftpException
lists the contents of a remote directory.
Parameters:
path - a pattern relative to the current remote directory. The pattern can contain glob pattern wildcards (* or ?) in the last component (i.e. after the last /).
Returns:
a vector of ChannelSftp.LsEntry objects.
Throws:
SftpException

它要求您使用 glob 模式通配符。所以,我将通配符从

matchPattern = "*" + month + "*" + year + "*";

到

matchPattern = "*" + month + "??" + year + "*";

问题解决了。

感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 2013-03-13
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2013-05-22
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多