gpt4 book ai didi

java - Files.walk 识别文件是来自子文件夹还是主文件夹

转载 作者:行者123 更新时间:2023-12-02 11:32:35 26 4
gpt4 key购买 nike

我终于让我的 Files.walk 开始工作了,我的问题是是否有任何方法可以识别收集到列表中的文件是否来自子文件夹或主文件夹,因为这些文件有删除功能,但来自子文件夹的文件用户不应删除文件夹。

 private static List<FileInfo> listBackupFilesInLocalDir(String localPath, Predicate<String> fileNamePredicate) {
try (Stream<Path> files = Files.walk(Paths.get(localPath))) {
return files.filter(p -> fileNamePredicate.test(p.getFileName().toString()))
.map(p -> new FileInfo(p.getFileName().toString(), p.toFile().length()))
.sorted()
.collect(toList());
} catch (IOException e) {
log.error("Error listing directories", e);
throw new RuntimeException(e);
}
}

这是查找并收集所有文件的功能。这是我需要的某种过滤器,还是可以做我想做的事?

  deleteLocalFile.addClickListener(event -> {
try {
Files.delete(Paths.get(this.localStorage, String.valueOf(localFilesComboBox.getValue())));
} catch (IOException e) {
UI.getCurrent().access(() -> Notification.show(e.getMessage(), Notification.Type.ERROR_MESSAGE));
}

UI.getCurrent().access(() -> {
localFilesComboBox.removeAllItems();
localFilesComboBox.addItems(listBackupFiles());
});
});

上面是删除方法,我想要的只是像

if(from folder a) {
deny delete
}

或者类似的东西

最佳答案

好的,所以您希望能够仅删除主文件夹中的文件,并且仅删除文件,而不删除子文件夹中的文件。因此,您需要主文件夹中的文件列表。您可以通过从 listBackupFilesInLocalDir 方法的结果中检查 FileInfo 对象的 URL 来完成此操作。这可以通过以下方式完成:

public ArrayList<FileInfo> filesInMainFolder(string mainPath,
ArrayList<FileInfo> files) {
ArrayList<FileInfo> res = new ArrayList<FileInfo>();

for (FileInfo info : files) {
String url = info.getUrl().toString();
// Get the path of the File for which we have file information
url = url.substring(0, url.lastIndexOf('/'));

// Is file in the main folder
if (url.compareTo(mainPath) == 0 && info.isDirectory() == false) {

res.add(info);
}
}
return res;
}

该方法应该相当容易遵循。我这里没有包含的选项是 getUrl() URL 上的方法,因为我不能 100% 确定它是如何工作的。如果它获取目录路径,请使用它并放弃对 url 字符串的转换,只需使用 info.getUrl().getPath()

关于java - Files.walk 识别文件是来自子文件夹还是主文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49194082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com