Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change file name and its extension before output it Java

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.

like image 289
Best Avatar asked Dec 02 '22 00:12

Best


2 Answers

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));
like image 156
Aviram Segal Avatar answered Feb 13 '23 23:02

Aviram Segal


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");
like image 28
Jesper Avatar answered Feb 14 '23 00:02

Jesper