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

时间:2015-04-12 19:55:52

标签: java file-upload file-io apache-commons-fileupload

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

在我的情况下,我想在上传时重命名文件。我正在使用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文件上传库有什么好办法吗?

1 个答案:

答案 0 :(得分:1)

尝试拆分并仅采用扩展程序的拆分:

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