我正在编写一个程序,其中涉及编辑文件并用路径替换占位符。
这是代码:
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);
Run Code Online (Sandbox Code Playgroud)
基本路径“游戏”文件路径没有问题,因为在我程序的所有其他位置,它都包含斜杠。仅在此部分中替换不包含斜杠的占位符。
例如,它不是C:/ Users \ name \ Documents \ program \ Game,而是返回UsersnameDocumentsprogramGame。
就像我之前说的,在所有其他地方,它返回正确的路径名(带有斜线)。在Mac上,所有斜线都存在,即使在这一部分也是如此。
有人知道解决方法吗?谢谢。
从String.replaceAll方法的文档中:
请注意,替换字符串中的反斜杠(
\)和美元符号($)可能导致结果与被视为文字替换字符串的结果有所不同;见Matcher.replaceAll。使用Matcher.quoteReplacement抑制这些字符的特殊含义,如果需要的话。