我一直在使用sshj库
<dependency>
<groupId>net.schmizz</groupId>
<artifactId>sshj</artifactId>
<version>0.3.1</version>
</dependency>
以下是我的代码使用0.3.1,它可以很好地上传支持通配符模式的文件。
SSHClient client = null;
SCPUploadClient uploader = null;
try {
client = getClient();
uploader = client.newSCPFileTransfer().newSCPUploadClient();
uploader.setFileFilter(new WildcardFileFilter(wildCardPattern));
//determine the remote directory
File f = new File(localDirLocation);
String dir = remoteDirLocation + f.getName();
uploader.copy(localDirLocation, remoteDirLocation);
} catch (IOException e) {
//processing exceptions here
} finally {
disconnectClient(client);
}
但是现在代码在我尝试移动到0.5.0时给了我很多编译错误。
我想了解当我想从本地到远程机器上传和下载文件时如何设置fileFilters,反之亦然
有人可以帮帮我吗?
答案 0 :(得分:3)
目前使用0.5.0已不再可行。我为SSHJ的Shikhar(维护者)创建了一个pull request。
下面我调整了您的代码示例,使其与0.5.0一起使用。基本的变化是您现在需要为copy方法提供LocalSourceFile。为了使SCPUploadClient只能发送目录的过滤内容,我已经覆盖了getChildren(LocalFileFilter)方法。
SSHClient client = null;
SCPUploadClient uploader = null;
try {
client = getClient();
uploader = client.newSCPFileTransfer().newSCPUploadClient();
File f = new File(localDirLocation);
FilteredFileSystemDirectory filteredDir = new FilteredFileSystemDirectory(f, new WildcardFileFilter());
String dir = remoteDirLocation + f.getName();
uploader.copy(filteredDir, remoteDirLocation);
} catch (IOException e) {
//processing exceptions here
} finally {
disconnectClient(client);
}
public class FilteredFileSystemDirectory extends FileSystemFile {
private final LocalFileFilter filter;
public FilteredFileSystemDirectory(File f, LocalFileFilter filter) {
super(f);
this.filter = filter;
}
@Override
public Iterable<? extends LocalSourceFile> getChildren(LocalFileFilter filter)
throws IOException {
return super.getChildren(filter);
}
}
对于WildcardFileFilter,请参阅我的第二个答案,了解如何在0.6.0中执行此操作。
希望这有帮助。
答案 1 :(得分:0)
使用0.6.0,您可以按如下方式编写代码:
SSHClient client = null;
SCPUploadClient uploader = null;
try {
client = getClient();
uploader = client.newSCPFileTransfer().newSCPUploadClient();
uploader.setUploadFilter(new WildcardFileFilter(wildCardPattern));
//determine the remote directory
File f = new File(localDirLocation);
String dir = remoteDirLocation + f.getName();
uploader.copy(new FileSystemFile(localDirLocation), remoteDirLocation);
} catch (IOException e) {
//processing exceptions here
} finally {
disconnectClient(client);
}
你使用的WildcardFileFilter来自公地 - 我想。因为这是一个FilenameFilter而不是LocalFileFilter,你可以非常简单地实现它:
public WildcardFileFilter implements LocalFileFilter {
private String wildcardPattern;
public WildcardFileFilter(String wildcardPattern) {
this.wildcardPattern = wildcardPattern;
}
@Override
public boolean accept(LocalSourceFile file) {
return FilenameUtils.wildcardMatchOnSystem(file.getName(), wildcardPattern);
}
}