java:如何将文本附加到某个索引后的字符串中

java:如何将文本附加到某个索引后的字符串中,java,string,Java,String,我有一条路 C:\Users\abc xyz\Desktop\test.docx 我想换成 C:\Users\sara waheed\Desktop\~$sara.docx 首先,我得到了反斜杠的最后一个索引,现在我想在最后一个反斜杠后面加上“~$” String str=path.toString(); int index = str.lastIndexOf('\\'); 注意 我事先不知道这条路的价值 如何实现这一点通常,在操作路径时应该使用java.nio.file API,这样可

我有一条路

C:\Users\abc xyz\Desktop\test.docx 
我想换成

C:\Users\sara waheed\Desktop\~$sara.docx
首先,我得到了反斜杠的最后一个索引,现在我想在最后一个反斜杠后面加上“~$”

String str=path.toString();
int index = str.lastIndexOf('\\');
注意 我事先不知道这条路的价值


如何实现这一点通常,在操作路径时应该使用java.nio.file API,这样可以避免依赖于平台的假设

String str = path.getFileName().toString();
// The string concatenation way:
if(str.endsWith(".docx")) { // should we check the beginning of fname?
                              // maybe it already has the prefix?
    path = path.resolveSibling("~$" + str);
}
System.out.println(path);

因为您要表示文件,所以我建议使用api。您可以修改路径的任何部分,而不会影响其他部分

Path file = Paths.get("C:\\Users\\abc xyz\\Desktop\\test.docx");
Path lock = file.resolveSibling("~$" + file.getFileName());
要与这些路径交互,请继续查看Files类

Files.touch(lock);
或者通过
path.toFile()使用经典方法


顺便说一下,这些都在
java.nio.file
包中。

你不是15分钟前才问过这个问题吗?不管怎样。。。如果你知道索引,你可以用它来裁剪需要的部分。从那以后,它应该是简单的字符串连接。你只是问了这个问题,被告知如何做,得到了一个指向文档的链接,然后删除了你的问题。别这么懒。阅读文档,并尝试这样做。或者学习编程以外的知识,因为阅读文档和尝试编写代码是它的全部内容。