Change file name and its extension before output it Java

21,254

Solution 1

Just rename the file:

File file = new File(oldFilepath);
boolean success = file.renameTo(new File(newFilepath));

You could also just give a filename and use the same parent as your current file:

File file = new File(oldFilepath);
file.renameTo(new File(file.getParentFile(), newFilename));

Solution 2

It's not really clear what exactly you want; I hope this answer is useful to you.

Suppose you have a java.io.File object that represents D:\work\2012\018\08\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01, and that you want to have a File object that represents D:\work\2012\018\08\mywork.pdf. You already know the new filename mywork.pdf but you want to get the directory name from the original File object. You can do that like this:

File original = new File("D:\\work\\2012\\018\\08\\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01");

// Gets the File object for the directory that contains the file
File dir = original.getParentFile();

// Creates a File object for a file in the same directory with the name "mywork.pdf"
File result = new File(dir, "mywork.pdf");
Share:
21,254
Best
Author by

Best

I´m a new developer who's currently working on tools which invloved Java, JSP, JSF and other java technologies.

Updated on July 09, 2022

Comments

  • Best
    Best almost 2 years

    Lets say I've got a file in D: which has a filepath as:

            D:\work\2012\018\08\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01
    

    at the moment the name of this file is not meaningful. It doesn't have a format. I would like to have the ability to create file object from the above filepath in Java and change its name and format before writing it into bytes. The new path could be as following:

           D:\work\2012\018\08\mywork.pdf
    

    After the changes have been made, I should still be able to gain access to the original file per normal.

    I already know the type of the file and its name so there won't be a problem getting those details.