Reputation: 3
I have below mentioned full path string:
String originalpath = C:\test\sample\batchmatch\internal\a\b\a.pdf
I need to replace first part of the path with new path
For example:
oldpath = C:\test\sample\batchmatch\internal\to
new path = C:\testdemo\sampledemo\batchmatchdemo\internal
I have tried below mentioned approach, but it doesn't work.
String newpath = originalpath.replaceAll(oldpath,newpath);
Could you please help me?
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 );
}
}
Upvotes: 0
Views: 322
Reputation: 300
There are several methods to do this as for example :
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
path : C:/testdemo/sampledemo/batchmatchdemo/internal/a/b/a.pdf
Upvotes: 0
Reputation: 7916
This should be a bit flexible for you irrespective of your platform (i.e \
or /
)
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);
Upvotes: 1
Reputation: 967
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);
}
Upvotes: 0