Java Files.walk标识文件是来自子文件夹还是主文件夹
我终于找到了我的文件。现在我的问题是,是否有任何方法可以确定收集到列表中的文件是否来自子文件夹或主文件夹,因为这些文件有删除功能,但用户不能删除子文件夹中的文件Java Files.walk标识文件是来自子文件夹还是主文件夹,java,filter,stream,Java,Filter,Stream,我终于找到了我的文件。现在我的问题是,是否有任何方法可以确定收集到列表中的文件是否来自子文件夹或主文件夹,因为这些文件有删除功能,但用户不能删除子文件夹中的文件 private static List<FileInfo> listBackupFilesInLocalDir(String localPath, Predicate<String> fileNamePredicate) { try (Stream<Path> files = Files.w
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);
}
}
上面是delete方法,我想要的只是一个iffrom文件夹{
拒绝删除
}
或者类似的要知道相对于localPath的深度,可以计算路径中的元素数。大概是这样的:
int mainFolderDepth = Paths.get(localPath).toRealPath().getNameCount();
//in your stream
int folderDepth = p.toRealPath().getNameCount();
if (! Files.isDirectory(p)) folderDepth--; //don't count the file name
if (folderDepth != mainFolderDepth) { /* not in main folder */ }
或者,在文件漫游中,如果要忽略子文件夹,请确保不输入子文件夹,方法是将maxDepth参数设置为1。好的,这样您就可以只删除主文件夹中的文件,只删除主文件夹中的文件,而不删除子文件夹中的文件。因此,您需要主文件夹中的文件列表。可以通过从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;
}
这个方法应该很容易遵循。我这里没有包括的选项是URL上的方法,因为我不能100%确定它是如何工作的。如果它获得了目录路径,则使用该路径,并放弃对url字符串的转换,只需使用info.getUrl.getPath函数返回之前还是之后执行此操作?因为一个简单的解决方案是重复列表,看看文件是否在文件夹a或bIt中,不管是在之前还是之后,只要我可以检查我的删除文件方法,如果文件来自文件夹a或b
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;
}