Android 通过文件路径直接修改文件名

今天遇到一个录制视频需要修改文件路径的,因为开始录制视频的时候已经生成文件名称才去录制视频,解决办法就是录制视频结束后根据文件路劲修改文件名
下面直接贴代码

/**
* 2 * 通过文件路径直接修改文件名
* 3 *
* 4 * @param filePath 需要修改的文件的完整路径
* 5 * @param newFileName 需要修改的文件的名称
* 6 * @return
* 7
*/
public static String FixFileName(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 err) {
err.printStackTrace();
return null;
}
return newFilePath;
}

猜你喜欢

转载自blog.csdn.net/xieyaofeng/article/details/106139947