3

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?

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Manohar Gunturu
  • 676
  • 1
  • 10
  • 23

1 Answers1

2

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

Community
  • 1
  • 1
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88