java 如何使用java获取文件到文件夹的相对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5373582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:49:03  来源:igfitidea点击:

How to get the relative path of the file to a folder using java

javafile-io

提问by user496949

Possible Duplicate:
How to construct a relative path in Java from two absolute paths (or URLs)?

可能的重复:
如何从两个绝对路径(或 URL)构造 Java 中的相对路径?

using java, is there method to return the relative path of a file to a given folder?

使用java,是否有方法将文件的相对路径返回到给定文件夹?

回答by WhiteFang34

There's no method included with Java to do what you want. Perhaps there's a library somewhere out there that does it (I can't think of any offhand, and Apache Commons IO doesn't appear to have it). You could use this or something like it:

Java 中没有包含任何方法来执行您想要的操作。也许某处有一个库可以做到这一点(我想不出任何副手,而且 Apache Commons IO 似乎没有它)。你可以使用这个或类似的东西:

// returns null if file isn't relative to folder
public static String getRelativePath(File file, File folder) {
    String filePath = file.getAbsolutePath();
    String folderPath = folder.getAbsolutePath();
    if (filePath.startsWith(folderPath)) {
        return filePath.substring(folderPath.length() + 1);
    } else {
        return null;
    }
}