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
How to get the relative path of the file to a folder using java
提问by user496949
Possible Duplicate:
How to construct a relative path in Java from two absolute paths (or URLs)?
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;
}
}
回答by Aleadam
between File.getPath() and String.split() you should be all set to do it.
在 File.getPath() 和 String.split() 之间,你应该都准备好了。
http://download.oracle.com/javase/6/docs/api/java/io/File.html#getPath%28%29
http://download.oracle.com/javase/6/docs/api/java/io/File.html#getPath%28%29
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29