我有下面提到的完整路径字符串:
String originalpath = C:\test\sample\batchmatch\internal\a\b\a.pdf
我需要用新路径替换路径的第一部分
例如:
oldpath = C:\test\sample\batchmatch\internal\to
new path = C:\testdemo\sampledemo\batchmatchdemo\internal
我尝试了下面提到的方法,但它不起作用。
String newpath = originalpath.replaceAll(oldpath,newpath);
你能帮我吗?
class Demo {
public static void main(String[] args) {
String originalpath = C:\test\sample\batchmatch\internal\a\b\a.pdf;
String oldpath = C:\test\sample\batchmatch\internal\;
String newpath = C:\testdemo\sampledemo\batchmatchdemo\internal;
String relacepath = a.replaceAll(oldpath ,newpath);
System.out.println("replacepath::"+ relacepath );
}
}
答案 0 :(得分:1)
无论您的平台如何(\
或/
)
String oldPath = "C:\\test\\sample\\batchmatch\\internal\\a\\b\\a.pdf".replaceAll("(\\\\+|/+)", "/");
String newPath = "C:\\testdemo\\sampledemo\\batchmatchdemo\\internal".replaceAll("(\\\\+|/+)", "/");
String partToKeep = "\\a\\b\\a.pdf".replaceAll("(\\\\+|/+)", "/");
String partToReplace = oldPath.substring(0, oldPath.indexOf(partToKeep));
String replacedPath = oldPath.replaceAll(partToReplace, newPath).replaceAll("(\\\\+|/+)", Matcher.quoteReplacement(System.getProperty("file.separator")));
System.out.println(replacedPath);
答案 1 :(得分:0)
public static void main(String[] args) {
String originalpath = "C:/test/sample/batchmatch/internal/a/b/a.pdf";
String oldpath = "C:/test/sample/batchmatch/internal";
String path = "C:/testdemo/sampledemo/batchmatchdemo/internal";
System.out.println(originalpath);
String newpath = originalpath.replaceAll(oldpath,path);
System.out.println(newpath);
}
答案 2 :(得分:0)
有几种方法可以做到这一点,例如:
String communPath = "C:/test/sample/batchmatch/internal";
String secondpartOfPath = "/a/b/a.pdf";
String originalpath = communPath.concat(secondpartOfPath);
String newPath = "C:/testdemo/sampledemo/batchmatchdemo/internal";
System.out.println(originalpath);
String path = originalpath.replaceAll(communPath, newPath);
System.out.println(path );
originalpath:C:/test/sample/batchmatch/internal/a/b/a.pdf
路径:C:/testdemo/sampledemo/batchmatchdemo/internal/a/b/a.pdf