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