Normalizing slashes from string path in java

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

the number of slashes can be any number. How to normalize a path in java, for example:

 /var/lib/xen/images/rhel 
+4
source share
4 answers

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

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

You can use the File object to display the path defined for the current platform:

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

A couple more options:

A call to the # getCanonicalPath file occurs to remove the slashes, but it seemed to use this stack inside:

 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 pretty slow (at least on our particular system, which was Linux with GPFS below), so I couldn't use that.

So, I tried from Aubin's remote answer (thanks for saying that he might have seen in the JDK somewhere), it was actually pretty fast:

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

Unfortunately, under the toURI method, it seemed like 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 little slowdown.

See also java nio Paths # normalize

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

+1
source

Use Guava CharMatcher :

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

See: Guava Explanation> Strings> CharMatcher

0
source

Source: https://habr.com/ru/post/1479392/


All Articles