[英]Java - copy from remote to local and delete source folder
我已經完成了到dest文件夾的邏輯復制,復制成功后刪除了源文件夾。 這是我的代碼,
File[] directories = new File("E:\\shareFolder")
.listFiles(file -> file.isDirectory() && file.getName().matches("[0-9]{6}"));
for (File getDirectory : directories) {
try {
FileUtils.copyDirectory(new File(getDirectory.getAbsolutePath()),new File("F:\\localFolder"));
// here i will check both file size are same if same
FileUtils.forceDelete(new File(getDirectory.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
但現在要求更改為遠程訪問源文件夾(E://shareFolder 到 \45.xx.88.xx\shareFolder)。
如何通過訪問遠程文件夾來實現現有的所有條件?
這與您使用 ssh 連接到主機時的情況相同,因為這就是 go 在幕后的情況。
正如評論中所建議的,您可以使用 JSch 庫maven文檔。
JSch ssh = new JSch();
Session session = ...
// create and configure session as needed, then connect
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
String pathToFile = ...
sftp.rm(pathToFile);
channel.disconnect();
session.disconnect();
編輯
如評論中所要求的,要僅刪除與正則表達式匹配的某些文件,您必須首先獲取與該正則表達式匹配的文件的名稱,然后對其進行迭代。 StackOverflow 上已經提供了一個示例。
使其適應您的情況
Vector ls = sftp.ls(path);
Pattern pattern = Pattern.compile("[0-9]{6}");
for (Object entry : ls) {
ChannelSftp.LsEntry e = (ChannelSftp.LsEntry) entry;
Matcher m = pattern.matcher(e.getFilename());
if (m.matches()) {
sftp.rm(e.getFilename());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.