2012-06-08 34 views
2

我有一个java文件路径如何解析java中的文件名?

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

我要替换的文件路径 这里的根路径将保持不变,但要更改文件名从myfile.jarTest.xml

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

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

回答

5

检查出Java Commons IOFilenameUtils类。

具有用于可靠拆卸和在不同的平台操作的文件名的多种方法(这是值得考虑的许多其他有用的实用程序太)。

+1

恕我直言该文件,如果第三方lib中你想要做什么o不要,使用该库。特别是当它来自Apache。甚至当库名称以“commons”开头时更是如此。 –

+2

但是不要添加第三方的lib这个简单的东西,可以在一行标准的JDK代码中完成(是的,我知道答案有2或3行,但这些可以结合,因为最有可能的中间父文件新文件创建后不需要变量)。 – Matt

9

这是正确的方式做到这一点:

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 
2
File f = new File("/opt/test/myfolder/myinsidefolder/myfile.jar"); 
File path = f.getParentFile(); 
File xml = new File(path, "Test.xml"); 
2

只使用JRE提供一流File一种更直接的方法:

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

要重命名,你可以使用Files.move从java.nio.file.Files

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!"); 
} 
+0

最好添加一些代码说明! –