[英]How to parse file name in java?
我有一個java文件路徑
/opt/test/myfolder/myinsidefolder/myfile.jar
我想將文件路徑替換為這里的根路徑將保持相同但希望將文件名從myfile.jar
更改為Test.xml
/opt/test/myfolder/myinsidefolder/Test.xml
我怎么能在java中做任何幫助?
這是正確的方法:
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
查看Java Commons IO FilenameUtils類。
這有許多方法可以在不同的平台上可靠地分解和操作文件名(值得看看許多其他有用的實用程序)。
File f = new File("/opt/test/myfolder/myinsidefolder/myfile.jar");
File path = f.getParentFile();
File xml = new File(path, "Test.xml");
僅使用JRE可用類文件的更直接方法:
String parentPath = new File("/opt/test/myfolder/myinsidefolder/myfile.jar").getParent();
new File(parentPath, "Test.xml");
要重命名該文件,您可以使用java.nio.file.Files中的Files.move
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!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.