3

I have a java file path

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

I want to replace the file path to here root path will remain same but want to change file name from myfile.jar to Test.xml

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

How can i do this in java any help?

5 Answers 5

11

Using Java 9+

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

Using Java 8 and older

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

Or, if you prefer working with strings only:

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
Sign up to request clarification or add additional context in comments.

Comments

6

Check out the Java Commons IO FilenameUtils class.

That has numerous methods for reliably disassembling and manipulating filenames across different platforms (it's worth looking at for many other useful utilities too).

2 Comments

IMHO, if a third party lib does what you want o do, use that lib. Especially when it comes from apache. And even more so when the libs name starts with "commons".
But don't add a third party lib for something this simple that can be accomplished in a single line of standard JDK code (yes i know the answers have 2 or 3 lines, but those could be combined since most likely the intermediate parent file variables are not needed after the new file creation).
2
File f = new File("/opt/test/myfolder/myinsidefolder/myfile.jar");
File path = f.getParentFile();
File xml = new File(path, "Test.xml");

Comments

2

A more direct approach using only JRE available class File :

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

Comments

0

To rename the file you can use Files.move from 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!");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.