检查文件是否属于给定文件夹或其子文件夹 - eclipse插件

时间:2015-12-23 09:34:53

标签: eclipse eclipse-plugin directory filepath subdirectory

我正在尝试创建一个eclipse插件。我需要检查给定文件是否属于给定文件夹或其子文件夹。文件夹的路径作为用户的输入。该文件可能直接属于文件夹内部,也可能位于子文件夹的深处。我怎样才能实现这种检查?如果它属于文件夹/子文件夹,则返回整个文件路径。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

解决方案是通过递归检查文件是否属于该文件夹。这是代码:`

    public static void checkDirectoryContents(File dir,String filename) {
    try {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("directory:" + file.getCanonicalPath());
                checkDirectoryContents(file,filename);
            } else {
                System.out.println("\nFile name and path found" + file.getName() +" " +file.getCanonicalPath());

                if(file.getName().equals(filename)) {
                    System.out.println("\nFile name and path found !!!!!!!" + file.getName() +" " +file.getCanonicalPath());
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}`

答案 1 :(得分:0)

检查确实有意义,如果根文件夹或子文件夹的路径中可以有“ ..”。在这种情况下,getCanonicalPath()可以帮助您获取处理了“ ..”条目并从结果中删除的相应完整路径。例如。应该使用这种检查来防止诸如“ zip slip”之类的问题。

File rootFolder = ...;
File subFolderOrFile = ...;
if (rootFolder.getCanonicalPath().startsWith(subFolderOrFile.getCanonicalPath()) {
    // subFolderOrFile is truely uder the rootFolder
}