gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:05:37 25 4
gpt4 key购买 nike

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

在我的例子中,我想在上传文件时重命名文件。我正在使用 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

关于java - 在java中保留文件扩展名的同时重命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com