Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename the file while preserving file extension in java

How to rename a file by preserving file extension?

In my case I want to rename a file while uploading it. I am using Apache commons fileupload library.

Below is my code snippet.

File uploadedFile = new File(path + "/" + fileName);

item.write(uploadedFile);
//renaming uploaded file with unique value.          
String id = UUID.randomUUID().toString();
File newName = new File(path + "/" + id);
if(uploadedFile.renameTo(newName)) {

} else {
    System.out.println("Error");
}

The above code is changing the file extension too. How can I preserve it? Is there any good way with apache commons file upload library?

like image 293
Manohar Gunturu Avatar asked Dec 29 '25 02:12

Manohar Gunturu


1 Answers

Try to split and take only the extension's split:

String[] fileNameSplits = fileName.split("\\.");
// extension is assumed to be the last part
int extensionIndex = fileNameSplits.length - 1;
// add extension to id
File newName = new File(path + "/" + id + "." + fileNameSplits[extensionIndex]);

An example:

public static void main(String[] args){
    String fileName = "filename.extension";
    System.out.println("Old: " + fileName);
    String id = "thisIsAnID";
    String[] fileNameSplits = fileName.split("\\.");
    // extension is assumed to be the last part
    int extensionIndex = fileNameSplits.length - 1;
    // add extension to id
    System.out.println("New: " + id + "." + fileNameSplits[extensionIndex]);
}

BONUS - CLICK ME

like image 81
Reut Sharabani Avatar answered Dec 30 '25 16:12

Reut Sharabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!