FileUtil { public static String canonicalize(CharSequence path) { String newPath = path.toString(); Matcher matcher = PARENT_DIR.matcher(newPath); while (matcher.find()) { StringBuffer sb = new StringBuffer(); matcher.appendReplacement(sb, matcher.group(2).isEmpty() ? "" : matcher.group(1).replace("\\", "\\\\")); matcher.appendTail(sb); newPath = sb.toString(); matcher.reset(newPath); } return newPath; } private  FileUtil(); static String joinPath(String... elements); static void forceMkdirs(File dir); static void safeCopyFile(File child, File destChild); static void writeAndForce(Path path, byte[] data); static String canonicalize(CharSequence path); static File canonicalize(File file);  }
@Test public void testCanonicalize() { Assert.assertEquals("bat.txt", FileUtil.canonicalize("foo/../bat.txt")); Assert.assertEquals("bat.txt", FileUtil.canonicalize("foo/bar/../../bat.txt")); Assert.assertEquals("foo/", FileUtil.canonicalize("foo/bar/../")); Assert.assertEquals("foo", FileUtil.canonicalize("foo/bar/..")); Assert.assertEquals("../bat.txt", FileUtil.canonicalize("../bat.txt")); Assert.assertEquals("/bat.txt", FileUtil.canonicalize("/foo/bar/../../bat.txt")); Assert.assertEquals("/bar/bat.txt", FileUtil.canonicalize("/foo/../bar/bat.txt")); }
@Test public void testCanonicalizeWindoze() { Assert.assertEquals("bat.txt", FileUtil.canonicalize("foo\\..\\bat.txt")); Assert.assertEquals("bat.txt", FileUtil.canonicalize("foo\\bar\\..\\..\\bat.txt")); Assert.assertEquals("foo\\", FileUtil.canonicalize("foo\\bar\\..\\")); Assert.assertEquals("foo", FileUtil.canonicalize("foo\\bar\\..")); Assert.assertEquals("..\\bat.txt", FileUtil.canonicalize("..\\bat.txt")); Assert.assertEquals("\\bat.txt", FileUtil.canonicalize("\\foo\\bar\\..\\..\\bat.txt")); Assert.assertEquals("\\bar\\bat.txt", FileUtil.canonicalize("\\foo\\..\\bar\\bat.txt")); Assert.assertEquals("C:\\bar\\bat.txt", FileUtil.canonicalize("C:\\foo\\..\\bar\\bat.txt")); }