在 java 中重命名文件同时保留文件扩展名

Rename the file while preserving file extension in java

如何通过保留文件扩展名来重命名文件?

就我而言,我想在上传文件时重命名文件。我正在使用 Apache commons fileupload 库。

下面是我的代码片段。

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");
}

上面的代码也改变了文件扩展名。我怎样才能保存它? apache commons文件上传库有什么好的方法吗?

尝试拆分并只采用扩展的拆分:

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]);

一个例子:

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