Reputation: 135
I am making a program that involves editing a file and replacing a placeholder with a path.
Here is the code:
List<String> lines = Files.readAllLines(new File(new File(basepath, "Game"), "launcher_profiles.json").toPath());
int index = -1;
for (String s : lines){
index++;
if (s.contains("PROGRAM/GAMEDIRPATH")) break;
}
String k = lines.get(index);
k = k.replaceAll("PROGRAM/GAMEDIRPATH", new File(basepath, "Game").getPath());
lines.set(index, k);
clearFile(new File(new File(basepath, "Game"), "launcher_profiles.json"));
Files.write(new File(new File(basepath, "Game"), "launcher_profiles.json").toPath(), lines, StandardOpenOption.CREATE);
There is no problem with the basepath, "Game" file path because in every other place in my program, it includes the slashes. It is only in this part where it is replacing the placeholder that does not include slashes.
For example, instead of being C:/Users\name\Documents\program\Game, it returns UsersnameDocumentsprogramGame.
As I said previously, in all other places, it returns the correct path name (with the slashes). On a Mac, all slashes are there, even in this part.
Does anyone know a fix? Thank you.
Upvotes: 1
Views: 413
Reputation: 1066
You have used replaceAll method to replace a part of string with something else. I think The first argument of replaceAll method take a string but it is treated as a regular expression and i think the slash in the argument "PROGRAM/GAMEDIRPATH" triggers something.
just remove the replaceAll method and use replace method because replace() method takes characterSequence as argument. This is not the solution for replacing all the string but at least you will know the cause.
k = k.replace("PROGRAM/GAMEDIRPATH", new File(basepath, "Game").getPath());
edit: your code works fine on linux, it shows the value of k as /home/userName/Documents/Game
On windows, you might have to search for escape character when using regex
Upvotes: 1
Reputation: 1554
From the String.replaceAll
method's documentation:
Note that backslashes (
\
) and dollar signs ($
) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; seeMatcher.replaceAll
. UseMatcher.quoteReplacement
to suppress the special meaning of these characters, if desired.
Upvotes: 5