Check if file is in (sub)directory

前端 未结 8 945
醉梦人生
醉梦人生 2021-01-04 05:50

I would like to check whether an existing file is in a specific directory or a subdirectory of that.

I have two File objects.

File dir;
File file;
<         


        
8条回答
  •  被撕碎了的回忆
    2021-01-04 06:07

    You can do this, however it won't catch every use case e.g. dir = /somedir/../tmp/dir/etc..., unless that's how the file was defined also.

    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    public class FileTest {
        public static void main(final String... args) {
            final Path dir = Paths.get("/tmp/dir").toAbsolutePath();
            final Path file = Paths.get("/tmp/dir/subdir1/subdir2/file.txt").toAbsolutePath();
            System.out.println("Dir: " + dir);
            System.out.println("File: " + file);
            final boolean valid = file.startsWith(dir);
            System.out.println("Valid: " + valid);
        }
    }
    

    In order for the checks to work correctly, you really need to map these using toRealPath() or, in your example, getCanonicalPath(), but you then have to handle exceptions for these examples which is absolutely correct that you should do so.

提交回复
热议问题