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


 1     /**
 2      * 通过文件路径直接修改文件名
 3      * 
 4      * @param filePath    需要修改的文件的完整路径
 5      * @param newFileName 需要修改的文件的名称
 6      * @return
 7      */
 8     private String FixFileName(String filePath, String newFileName) {
 9         File f = new File(filePath);
10         if (!f.exists()) { // 判断原文件是否存在(防止文件名冲突)
11             return null;
12         }
13         newFileName = newFileName.trim();
14         if ("".equals(newFileName) || newFileName == null) // 文件名不能为空
15             return null;
16         String newFilePath = null;
17         if (f.isDirectory()) { // 判断是否为文件夹
18             newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName;
19         } else {
20             newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName
21                     + filePath.substring(filePath.lastIndexOf("."));
22         }
23         File nf = new File(newFilePath);
24         try {
25             f.renameTo(nf); // 修改文件名
26         } catch (Exception err) {
27             err.printStackTrace();
28             return null;
29         }
30         return newFilePath;
31     }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM