我正在制作一个涉及编辑文件并用路径替换占位符的程序。
代码如下:
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);
基本路径“游戏”文件路径没有问题,因为在我程序的所有其他地方,它都包含斜杠。仅在这部分替换不包含斜杠的占位符。
例如,而不是 C:/Users\name\Documents\program\Game,返回UsersnameDocumentsprogramGame。
正如我之前所说,在所有其他地方,它返回正确的路径名(带斜线)。 在 Mac 上,所有斜杠都在那里,即使在这一部分也是如此。
有人知道解决办法吗?谢谢。
最佳答案
来自 String.replaceAll
方法的文档:
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.
关于java - getPath() 不返回斜杠? ( window ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44810727/