-2

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

  • Look into [`System.getProperty(String)`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getProperty-java.lang.String-) – phflack Dec 04 '17 at 19:28

2 Answers2

0

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")

phflack
  • 2,729
  • 1
  • 9
  • 21
0

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--

tribone
  • 13
  • 4