简体   繁体   中英

Python os.path.dirname and os.path.sep in Java?

Python has os.path.dirname and os.path.sep. How can I get these values in Java?

Did a bit of googling on what os.path.dirname and os.path.sep actually are

os.path.dirname(path) would be filePath.split(System.getProperty("path.separator"))[0]

os.path.sep would be System.getProperty("file.separator")

The accepted answer is not correct for os.path.dirname . Paths.get(path).getParent() is the Java equivalent.

In [1]: import os

In [2]: os.path.dirname("/foo/bar/bax.txt")
Out[2]: '/foo/bar'

In [3]: os.path.dirname("/foo/bar")
Out[3]: '/foo'
jshell> import java.nio.file.Paths;

jshell> Paths.get("/foo/bar/baz.txt").getParent()
$2 ==> /foo/bar

jshell> Paths.get("/foo/bar").getParent()
$3 ==> /foo

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html#getParent--

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM