在Java中,是否将文件路径转换为规范形式?
我想编写一个算法,将任意文件路径转换为规范形式(即删除任何“.”和“.”其中“.”表示“当前目录”,“以及“.”表示“上一级”)。我已经删除了“.”正确,这部分很容易 例如:在Java中,是否将文件路径转换为规范形式?,java,file,filepath,canonical-link,Java,File,Filepath,Canonical Link,我想编写一个算法,将任意文件路径转换为规范形式(即删除任何“.”和“.”其中“.”表示“当前目录”,“以及“.”表示“上一级”)。我已经删除了“.”正确,这部分很容易 例如: /web/foo/bar/../baz/../../blat/./../foobie/bletch.html 应该成为 /web/foobie/bletch.html www/someDir/index.html www/index.html 及 应该成为 /web/foobie/bletch.html www/
/web/foo/bar/../baz/../../blat/./../foobie/bletch.html
应该成为
/web/foobie/bletch.html
www/someDir/index.html
www/index.html
及
应该成为
/web/foobie/bletch.html
www/someDir/index.html
www/index.html
及
应该成为
/web/foobie/bletch.html
www/someDir/index.html
www/index.html
这是我目前的代码:
public static String makeCanonical(String uri) {
String canonical="";
System.out.println("+" + uri); //for testing, doesn't need to print
ArrayList<String> parts=new ArrayList<String>();
int currentIndex=0;
//split string at every '/' into an ArrayList substring
for(int i=0; i<uri.length(); i++){
if(uri.charAt(i)=='/'){
parts.add(uri.substring(currentIndex, i+1));
currentIndex=i+1;
}
}
//trying to go up one level at every '..' ; not working correctly
for(int i=0; i<parts.size(); i++){
if(parts.get(i).contains("..")){
parts.remove(i);
parts.remove(i-1);
}
}
//compile all parts into single string
for(int i=0; i<parts.size(); i++){
canonical=canonical+parts.get(i);
}
//discard and '.' (single dot) characters
canonical=canonical.replaceAll("/./", "/");
if(canonical.contains(".")){
}
System.out.print("-" + canonical); //printing for testing
System.out.println();
System.out.println();
return canonical;
}
-
这是一个练习?为什么不使用
java.nio.file.Path
?或者看看它的一些内置实现?这是一个开始。现在,你的尝试有什么问题?这是家庭作业?您不能使用任何内置功能?据我所知,您还没有发现的另一个错误:replaceAll(“/./”,…
应用于/x/
将导致/
,因为该方法假定您提供的是正则表达式,
表示“任何字符”不是文本
。例如replaceAll(“/\\./”
或使用。replace(“/./”,“/”)
它也取代了所有但不采用正则表达式语法,是一个很好的不满足命名的例子。这是一个练习?你为什么不使用java.nio.file.Path
?或者看看它的一些内置实现?这是一个开始。现在,你的尝试有什么问题吗?这是家庭作业?你不能使用任何内置函数City?据我所知,您还没有发现的另一个错误:replaceAll(“/./”),应用于/x/
的将导致/
,因为该方法假定您提供的是正则表达式,
表示“任何字符”,而不是文本
。例如replaceAll(“/\./”
或使用.replace(“/。/”,“/”)
,它也替换了所有但不采用正则表达式语法,是不一致命名的一个很好的例子。