如何在Java中解析文件名?

v64noz0r  于 2023-02-14  发布在  Java
关注(0)|答案(5)|浏览(158)

我有一个java文件路径
/opt/test/myfolder/myinsidefolder/myfile.jar
我想将文件路径替换为此处根路径将保持不变,但想将文件名从myfile.jar更改为Test.xml
/opt/test/myfolder/myinsidefolder/Test.xml
我怎样才能做到这一点在java任何帮助?

3bygqnnd

3bygqnnd1#

使用Java 9+

Path jarPath = Paths.get("/opt/test/myfolder/myinsidefolder/myfile.jar");
Path xmlPath = jarPath.resolveSibling("Test.xml");

使用Java 8及更早版本

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
w6lpcovy

w6lpcovy2#

看看Java Commons IOFilenameUtils类。
它有许多方法可以在不同的平台上 * 可靠地 * 反汇编和操作文件名(对于许多其他有用的实用程序也值得一看)。

xienkqul

xienkqul3#

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

58wvjzkj4#

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

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

t5fffqht5#

要重命名文件,可以使用Files。move from java.nio. file。

File oldFile=new File("/opt/test/myfolder/myinsidefolder/myfile.jar");
File newFile=new File(oldFile.getParent+"/"+"Test.xml");
try
{
  Files.move(oldFile.toPath(),newFile.toPath());
}
catch (IOException ex)
{
  System.err.println("File was not renamed!");
}

相关问题