2017-04-06 7 views
0

への完全なパス文字列を古いパスを交換してください私は下記のアプローチを試したが、うまくいかない。私は以下の言及した新しいパス

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

あなたは 'replaceAll'のマニュアルを読みましたか?あなたの要件はあまり明確ではありません。 – tnw

+0

実行できない近似ではなく、問題を再現する実際の実行可能コードを表示します。参照:[mcve]を作成する方法。 –

+0

@tnw要件はC:\ test \ sample \ batchmatch \ internal \をC:\ testdemo \ sampledemo \ batchmatchdemo \ internalに置き換える必要があります。 – user7615212

答えて

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

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

例えばこれを行うには、いくつかの方法があります。

String communPath = "C:/test/sample/batchmatch/internal"; 
    String secondpartOfPath = "https://stackoverflow.com/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

関連する問題