Java 将旧路径替换为新路径

Java 将旧路径替换为新路径,java,Java,我在下面提到了完整路径字符串: 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 = or

我在下面提到了完整路径字符串:

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 );
    }
}

无论您的平台是什么(即
\
还是
/
),这对您来说都应该有点灵活


有几种方法可以做到这一点,例如:

    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 );
原始路径:C:/test/sample/batchmatch/internal/a/b/a.pdf


路径:C:/testdemo/sampledemo/batchmatchdemo/internal/a/b/a.pdf

您是否阅读了
replaceAll
的文档?您的需求不是很清楚。请展示您正在使用的再现问题的真正可运行代码,而不是无法运行的近似值。请参阅:如何创建。@tnw要求是我需要将C:\test\sample\batchmatch\internal\替换为C:\testdemo\sampledemo\batchmatchdemo\internal
    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);
    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 );