Java 有路径连接方法吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/711993/
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
Does Java have a path joining method?
提问by Geo
Exact Duplicate:
精确复制:
I would like to know if there is such a method in Java. Take this snippet as example :
我想知道Java中是否有这样的方法。以这个片段为例:
// this will output a/b
System.out.println(path_join("a","b"));
// a/b
System.out.println(path_join("a","/b");
采纳答案by Daniel LeCheminant
This concerns Java versions 7 and earlier.
这涉及 Java 版本 7 及更早版本。
To quote a good answer to the same question:
If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:
如果您希望稍后将其作为字符串返回,您可以调用 getPath()。事实上,如果你真的想模仿 Path.Combine,你可以这样写:
public static String combine (String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
回答by Soviut
One way is to get system properties that give you the path separator for the operating system, this tutorialexplains how. You can then use a standard string join using the file.separator
.
一种方法是获取为您提供操作系统路径分隔符的系统属性,本教程解释了如何操作。然后,您可以使用file.separator
.
回答by TofuBeer
This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.
这是一个开始,我不认为它完全按照您的意图工作,但它至少会产生一致的结果。
import java.io.File;
public class Main
{
public static void main(final String[] argv)
throws Exception
{
System.out.println(pathJoin());
System.out.println(pathJoin(""));
System.out.println(pathJoin("a"));
System.out.println(pathJoin("a", "b"));
System.out.println(pathJoin("a", "b", "c"));
System.out.println(pathJoin("a", "b", "", "def"));
}
public static String pathJoin(final String ... pathElements)
{
final String path;
if(pathElements == null || pathElements.length == 0)
{
path = File.separator;
}
else
{
final StringBuilder builder;
builder = new StringBuilder();
for(final String pathElement : pathElements)
{
final String sanitizedPathElement;
// the "\" is for Windows... you will need to come up with the
// appropriate regex for this to be portable
sanitizedPathElement = pathElement.replaceAll("\" + File.separator, "");
if(sanitizedPathElement.length() > 0)
{
builder.append(sanitizedPathElement);
builder.append(File.separator);
}
}
path = builder.toString();
}
return (path);
}
}
回答by Peter Lawrey
You can just do
你可以做
String joinedPath = new File(path1, path2).toString();