Skip to content

Instantly share code, notes, and snippets.

@GrzegorzDrozd
Created January 15, 2014 10:23
Show Gist options
  • Save GrzegorzDrozd/8433939 to your computer and use it in GitHub Desktop.
Save GrzegorzDrozd/8433939 to your computer and use it in GitHub Desktop.
Normalize file system path in java.
import java.lang.System;
import java.util.regex.Matcher;
class NormalizePathSnippet {
public static void main(String[] args) {
// tests
System.out.println(normalizePath("foo\\abc"));
System.out.println(normalizePath("foo/abc"));
System.out.println(normalizePath("\\foo/abc"));
System.out.println(normalizePath("\\foo/abc"));
System.out.println(normalizePath("\\foo\\abc"));
System.out.println(normalizePath("\\foo/abc/"));
System.out.println(normalizePath("\\foo\\abc//"));
System.out.println(normalizePath("/foo/abc"));
System.out.println(normalizePath("/foo/abc"));
System.out.println(normalizePath("/foo\\abc"));
System.out.println(normalizePath("/foo/abc/"));
System.out.println(normalizePath("/foo\\abc//"));
System.out.println(normalizePath("/\\foo/abc"));
System.out.println(normalizePath("/\\foo/abc"));
System.out.println(normalizePath("/\\foo\\abc"));
System.out.println(normalizePath("/\\foo/abc/"));
System.out.println(normalizePath("/\\foo\\abc//"));
System.out.println(normalizePath("/foo/abc"));
System.out.println(normalizePath("/foo/abc"));
System.out.println(normalizePath("/foo\\abc"));
System.out.println(normalizePath("/foo/abc/"));
System.out.println(normalizePath("/foo\\abc//"));
}
public static String normalizePath(String path) {
// replace both types of slash
return path.replaceAll("(\\\\|/){1,}", Matcher.quoteReplacement(System.getProperty("file.separator")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment