在Python
中,我可以使用os.path.join
连接两条路径
os.path.join("foo", "bar") # => "foo/bar"
我正试图在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);
}
我原以为Path.resolve( )
会加入我当前的目录/home/user/test
,让data/foo.txt
制作/home/user/test/data/foo.txt
。我到底搞错了什么?
发布于 2015-12-25 10:34:32
不是特定的方法。
如果您使用的是java 8或更高版本,则有两个选择:
a)使用java.util.StringJoiner
StringJoiner joiner = new StringJoiner(File.pathSeparator); //Separator
joiner.add("path1").add("path2");
String joinedString = joiner.toString();
b)使用String.join(File.pathSeparator, "path1", "path2");
如果您使用的是java 7或更低版本,则可以使用apache commons中的commons-lang库。类StringUtils有一个使用分隔符连接字符串的方法。
c) StringUtils.join(new Object[] {"path1", "path2"}, File.pathSeparator);
附注:对于windows,您可以使用linux路径分隔符"/“(只需记住,绝对路径类似于"/C:/mydir1/mydir2”。如果使用诸如file://之类的协议,则始终使用"/“非常有用
发布于 2015-12-26 06:10:37
最基本的方法是:
Path filepath = Paths.get("foo", "bar");
您永远不应该编写Paths.get("")
。我很惊讶这能行得通。如果要显式引用当前目录,请使用Paths.get(System.getProperty("user.dir"))
。如果需要用户的主目录,请使用Paths.get(System.getProperty("user.home"))
。
您还可以将这些方法组合在一起:
Path filepath = Paths.get(
System.getProperty("user.home"), "data", "foo.txt");
发布于 2019-11-22 16:51:24
你可以这样做
// /root
Path rootPath = Paths.get("/root");
// /root/temp
Path temPath = rootPath.resolve("temp");
这里有一个很好的详细的帖子Path Sample Usecase
https://stackoverflow.com/questions/34459486
复制相似问题