在 Java 中连接路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34459486/
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
Joining paths in Java
提问by cybertextron
In Python
I can join two paths with os.path.join
:
在Python
我可以加入两条路径os.path.join
:
os.path.join("foo", "bar") # => "foo/bar"
I'm trying to achive the same in Java, without worrying if the OS
is Unix
, Solaris
or Windows
:
我正在尝试在 Java 中实现相同的目标,而不必担心OS
是Unix
,Solaris
或Windows
:
public static void main(String[] args) {
Path currentRelativePath = Paths.get("");
String current_dir = currentRelativePath.toAbsolutePath().toString();
String filename = "data/foo.txt";
Path filepath = currentRelativePath.resolve(filename);
// "data/foo.txt"
System.out.println(filepath);
}
I was expecting that Path.resolve( )
would join my current directory /home/user/test
with data/foo.txt
making /home/user/test/data/foo.txt
.
What am I getting wrong?
我期待那Path.resolve( )
会加入我的当前目录/home/user/test
与data/foo.txt
制作/home/user/test/data/foo.txt
。我怎么了?
采纳答案by YoungHobbit
Even though the original solution for getting the current directory using the empty String
works. But is recommended to use the user.dir
property for current directory and user.home
for home directory.
即使使用empty String
作品获取当前目录的原始解决方案。但建议user.dir
对当前目录和user.home
主目录使用该属性。
Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");
System.out.println(filePath.toString());
output:
输出:
/Users/user/coding/data/foo.txt
From Java Pathclass Documentation:
来自 Java Path类文档:
A Path is considered to be an empty path if it consists solely of one name element that is
empty
. Accessing a file using anempty path is equivalent to accessing the default directory
of the file system.
如果 Path 仅由一个名称元素组成,则该路径被视为空路径
empty
。使用empty path is equivalent to accessing the default directory
文件系统的访问文件。
Why Paths.get("").toAbsolutePath()
works
为什么Paths.get("").toAbsolutePath()
有效
When an empty string is passed to the Paths.get("")
, the returned Path
object contains empty path. But when we call Path.toAbsolutePath()
, it checks whether path length is greater than zero, otherwise it uses user.dir
system property and return the current path.
将空字符串传递给 时Paths.get("")
,返回的Path
对象包含空路径。但是当我们调用时Path.toAbsolutePath()
,它检查路径长度是否大于零,否则它使用user.dir
系统属性并返回当前路径。
Here is the code for Unix file system implementation: UnixPath.toAbsolutePath()
下面是 Unix 文件系统实现的代码:UnixPath.toAbsolutePath()
Basically you need to create the Path
instance again once you resolve the current directory path.
基本上,您需要在Path
解析当前目录路径后再次创建实例。
Also I would suggest using File.separatorChar
for platform independent code.
另外我建议使用File.separatorChar
平台独立代码。
Path currentRelativePath = Paths.get("");
Path currentDir = currentRelativePath.toAbsolutePath(); // <-- Get the Path and use resolve on it.
String filename = "data" + File.separatorChar + "foo.txt";
Path filepath = currentDir.resolve(filename);
// "data/foo.txt"
System.out.println(filepath);
Output:
输出:
/Users/user/coding/data/foo.txt
回答by CoderCroc
Paths#get(String first, String... more)
states,
Paths#get(String first, String... more)
状态,
Converts a path string, or a sequence of stringsthat when joined form a path string, to a
Path
....
A
Path
representing an emptypath is returned if first is the empty string and more does not contain any non-empty strings.
将路径字符串或连接形成路径字符串的字符串序列转换为
Path
....
如果 first 是空字符串并且 more 不包含任何非空字符串,则返回
Path
表示空路径的A 。
To get the current user directory you can simply use System.getProperty("user.dir")
.
要获取当前用户目录,您只需使用System.getProperty("user.dir")
.
Path path = Paths.get(System.getProperty("user.dir"), "abc.txt");
System.out.println(path);
Moreover, get
method uses variable length argumentof String
, which will be used to provide subsequent path strings. So, to create Path
for /test/inside/abc.txt
you have to use it in a following way,
此外,get
方法使用可变长度的参数的String
,其将被用于提供后续的路径串。因此,要Path
为/test/inside/abc.txt
您创建必须以以下方式使用它,
Path path = Paths.get("/test", "inside", "abc.txt");
回答by Rober2D2
Not an specific method.
不是具体的方法。
If you use java 8 or better, you have 2 options:
如果您使用 java 8 或更高版本,则有 2 个选项:
a) Use java.util.StringJoiner
a) 使用 java.util.StringJoiner
StringJoiner joiner = new StringJoiner(File.pathSeparator); //Separator
joiner.add("path1").add("path2");
String joinedString = joiner.toString();
b) Use String.join(File.pathSeparator, "path1", "path2");
b) 使用 String.join(File.pathSeparator, "path1", "path2");
If you use java 7 or lower, you may use commons-lang library from apache commons. The class StringUtils has a method to join strings using a separator.
如果您使用 java 7 或更低版本,则可以使用来自 apache commons 的 commons-lang 库。StringUtils 类有一个使用分隔符连接字符串的方法。
c) StringUtils.join(new Object[] {"path1", "path2"}, File.pathSeparator);
C) StringUtils.join(new Object[] {"path1", "path2"}, File.pathSeparator);
A sidenote: You may use linux pathseparator "/" for windows (Just remember that absolute paths are something like "/C:/mydir1/mydir2". Using always "/" is very useful if you use protocols such as file://
旁注:您可以在 Windows 中使用 linux 路径分隔符“/”(请记住,绝对路径类似于“/C:/mydir1/mydir2”。如果您使用诸如 file:// 之类的协议,始终使用“/”非常有用
回答by VGR
The most basic way is:
最基本的方法是:
Path filepath = Paths.get("foo", "bar");
You should never write Paths.get("")
. I'm surprised that works at all. If you want to refer to the current directory explicitly, use Paths.get(System.getProperty("user.dir"))
. If you want the user's home directory, use Paths.get(System.getProperty("user.home"))
.
你永远不应该写Paths.get("")
. 我很惊讶这有效。如果要明确引用当前目录,请使用Paths.get(System.getProperty("user.dir"))
. 如果您想要用户的主目录,请使用Paths.get(System.getProperty("user.home"))
.
You can also combine the approaches:
您还可以结合使用以下方法:
Path filepath = Paths.get(
System.getProperty("user.home"), "data", "foo.txt");
回答by Patrick Parker
The most reliable, platform-independent way to join paths in Java is by using Path::resolve
(as noted in the JavaDoc for Paths::get
). For an arbitrary-length array of Strings representing pieces of a path, these could be joined together using a Java Stream:
在 Java 中连接路径的最可靠、与平台无关的方法是使用Path::resolve
(如 JavaDoc for 中所述Paths::get
)。对于表示路径片段的任意长度字符串数组,可以使用 Java Stream 将它们连接在一起:
private static final String[] pieces = {
System.getProperty("user.dir"),
"data",
"foo.txt"};
public static void main (String[] args) {
Path dest = Arrays.stream(pieces).reduce(
/* identity */ Paths.get(""),
/* accumulator */ Path::resolve,
/* combiner */ Path::resolve);
System.out.println(dest);
}
回答by Robin Mathur
You can do like
你可以像
// /root
Path rootPath = Paths.get("/root");
// /root/temp
Path temPath = rootPath.resolve("temp");
A good detailed post is here Path Sample Usecase
一个很好的详细帖子在这里路径示例用例