/**
* 通過文件路徑直接修改文件名
*
* @param filePath 需要修改的文件的完整路徑
* @param newFileName 需要修改的文件的名稱
* @return
*/
private String changeFileName(String filePath, String newFileName) {
File f = new File(filePath);
if (!f.exists()) { // 判斷原文件是否存在(防止文件名衝突)
return null;
}
newFileName = newFileName.trim();
if ("".equals(newFileName) || newFileName == null) // 文件名不能爲空
return null;
String newFilePath = null;
if (f.isDirectory()) { // 判斷是否爲文件夾
newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName;
} else {
newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName
+ filePath.substring(filePath.lastIndexOf("."));
}
File nf = new File(newFilePath);
try {
f.renameTo(nf); // 修改文件名
} catch (Exception e) {
e.printStackTrace();
return null;
}
return newFilePath;
}