如何在java中解析文件名?

时间:2012-06-08 12:09:44

标签: java

我有一个java文件路径

/opt/test/myfolder/myinsidefolder/myfile.jar

我想将文件路径替换为 此处根路径将保持不变,但希望将文件名从myfile.jar更改为Test.xml

/opt/test/myfolder/myinsidefolder/Test.xml

我如何在java中做任何帮助?

5 个答案:

答案 0 :(得分:10)

这是正确的方法:

File myfile = new File("/opt/.../myinsidefolder/myfile.jar");
File test = new File(myfile.getParent(), "Test.xml");

或者,如果您更喜欢使用字符串:

String f = "/opt/test/myfolder/myinsidefolder/myfile.jar";
f = new File(new File(f).getParent(), "Test.xml").getAbsolutePath();

System.out.println(f); // /opt/test/myfolder/myinsidefolder/Test.xml

答案 1 :(得分:6)

查看Java Commons IO FilenameUtils课程。

有许多方法可以可靠地在不同平台上反汇编和操作文件名(值得关注许多其他有用的实用程序)。

答案 2 :(得分:2)

File f = new File("/opt/test/myfolder/myinsidefolder/myfile.jar");
File path = f.getParentFile();
File xml = new File(path, "Test.xml");

答案 3 :(得分:2)

仅使用JRE可用类File的更直接的方法:

String parentPath = new File("/opt/test/myfolder/myinsidefolder/myfile.jar").getParent();
new File(parentPath, "Test.xml");

答案 4 :(得分:0)

要重命名文件,您可以使用java.nio.file.Files中的Files.move

libdl