Amby
Amby

Reputation: 467

Normalizing slashes from a string path in java

String path = "/var/lib/////xen//images///rhel";

the number of slashes can be of any number. How to normalize the path in java like :

/var/lib/xen/images/rhel

Upvotes: 8

Views: 8369

Answers (4)

rogerdpack
rogerdpack

Reputation: 66741

A couple more options:

Calling File#getCanonicalPath happens to remove slashes, but it seemed to use this stack internally:

at java.io.UnixFileSystem.canonicalize0(Native Method)
at java.io.UnixFileSystem.canonicalize(UnixFileSystem.java:172)
at java.io.File.getCanonicalPath(File.java:618)

which seemed actually quite slow (at least on our particular system, which was Linux with GPFS underneath), so I couldn't use that.

So next I tried, from a deleted answer from Aubin (thanks! that he said he'd possibly seen in the JDK somewhere), this was actually quite a bit faster:

path = new File( new File( path ).toURI().normalize()).getPath();

Unfortunately underneath the toURI method seemed to call this:

    at java.io.UnixFileSystem.getBooleanAttributes0(Native Method)
    at java.io.UnixFileSystem.getBooleanAttributes(UnixFileSystem.java:242)
    at java.io.File.isDirectory(File.java:843)
    at java.io.File.toURI(File.java:732)

which was, again, a bit of slowdown.

See also java nio Paths#normalize

So at the end of the day, I ended up using the replaceAll methods from the others .

Upvotes: 1

Reimeus
Reimeus

Reputation: 159774

You could use a File object to output the path specific to the current platform:

String path = "/var/lib/////xen//images///rhel";
path = new File(path).getPath();

Upvotes: 5

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

Use Guava's CharMatcher:

String simplifiedPath = CharMatcher.is('/').collapseFrom(originalPath, '/');

See: Guava Explained > Strings > CharMatcher

Upvotes: 2

rgettman
rgettman

Reputation: 178263

Use the built-in String method replaceAll, with a regular expression "/+", replacing one or more slashes with one slash:

path = path.replaceAll("/+", "/");

Upvotes: 14

Related Questions