检查文件是否在(子)目录中 [英] Check if file is in (sub)directory

查看:117
本文介绍了检查文件是否在(子)目录中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查现有文件是在特定目录中还是在子目录中。

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

我有两个File对象。

I have two File objects.

File dir;
File file;

两者都保证存在。我们假设

Both are guaranteed to exist. Let's assume

dir  = /tmp/dir 
file = /tmp/dir/subdir1/subdir2/file.txt

我希望此检查返回true

I want this check to return true

现在我正在以这种方式进行检查:

For now i am doing the check this way:

String canonicalDir = dir.getCanonicalPath() + File.separator;
boolean subdir = file.getCanonicalPath().startsWith(canonicalDir);

这似乎适用于我的有限测试,但我不确定这是否会对某些操作产生问题系统。我也不喜欢getCanonicalPath()可以抛出我必须处理的IOException。

This seems to work with my limited tests, but i am unsure whether this might make problems on some operating systems. I also do not like that getCanonicalPath() can throw an IOException which i have to handle.

有更好的方法吗?可能在某些图书馆?

Is there a better way? Possibly in some library?

谢谢

推荐答案

我会创建一个小实用方法:

I would create a small utility method:

public static boolean isInSubDirectory(File dir, File file) {

    if (file == null)
        return false;

    if (file.equals(dir))
        return true;

    return isInSubDirectory(dir, file.getParentFile());
}

这篇关于检查文件是否在(子)目录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆