文件的重命名與移動操作
有時候為了對文件進行統一訪問與管理,需要把文件進行重命名,并移動到新的文件夾,如何實現呢?
一枚簡單的java/189240.html">java小程序即可實現:
part_1:需求:我需要把<(E:/BaiduYun/傳智播客_張孝祥_Java多線程與并發庫高級應用視頻教程下載)>文件夾下的所有子文件夾下的視頻文件重命名,并移動到新的位置<(E:/BaiduYun/張孝祥_Java多線程與并發庫)>;
part_2:目錄結構如下:
E:/BaiduYun
E:/BaiduYun/傳智播客_張孝祥_Java多線程與并發庫高級應用視頻教程下載
E:/BaiduYun/傳智播客張孝祥_Java多線程與并發庫高級應用視頻教程下載/01傳智播客張孝祥傳統線程技術回顧
part_3:程序源碼+注釋:
package cn.mike.demo;import java.io.File;import java.io.FileNotFoundException;import java.util.ArrayList;import java.util.List;/** * @author Administrator * @usage 該程序實現文件的重命名與移動操作; */public class RenameFiles { private static File srcFolder; // 源文件夾 private static File destFolder; // 目的文件夾 private static List<File> srcFiles; // 存放所有待命名的文件 static { srcFolder = new File("E://BaiduYun//傳智播客_張孝祥_Java多線程與并發庫高級應用視頻教程下載"); destFolder = new File("E://BaiduYun//張孝祥_Java多線程與并發庫"); srcFiles = new ArrayList<File>(); } public static void main(String[] args) { // 對文件夾的合法性(是否存在)進行校驗 try { checkFolder(); } catch (FileNotFoundException e) { e.printStackTrace(); return; } // 遍歷源文件夾把要修改的文件放到集合中 iterateGetFiles(RenameFiles.srcFolder); // 對集合中的元素進行重命名(并移動到目標文件夾) iterateRename(); } // end method-main private static void checkFolder() throws FileNotFoundException { if (!RenameFiles.srcFolder.exists()) { throw new FileNotFoundException("指定的源文件夾不存在."); } if (!RenameFiles.destFolder.exists()) { throw new FileNotFoundException("指定的目標文件夾不存在."); } } private static void iterateRename() { String aviName = null; String tempStr = null; StringBuilder strBuilder = new StringBuilder(); File tempFile = null; String sequenceNumber = null; String detailName = null; // 遍歷list集合,逐個進行重命名 for (File each : RenameFiles.srcFiles) { aviName = each.getName().substring(0, each.getName().length() - 4); // 獲取文件名稱(除去后綴名".avi") tempStr = each.getParent(); // 父文件夾的名稱 sequenceNumber = String.format("%02d", Integer.valueOf(aviName)); // 兩位的序號,不足兩位用0補齊,例如:01 detailName = tempStr.substring(tempStr.lastIndexOf("_") + 1); // 視頻文件的詳細內容,例如:傳統線程互斥技術 strBuilder.append(sequenceNumber + "_" + detailName + ".avi"); tempFile = new File(RenameFiles.destFolder, strBuilder.toString()); // 新文件的path // each.renameTo(tempFile);//核心代碼(實現重命名和移動) System.out.println(tempFile.toString()); // 打印到控制臺以便調試 strBuilder.delete(0, strBuilder.length()); // 切記將strBuilder進行清空 } // end foreach } // end method-iterateRename private static void iterateGetFiles(File srcFile) { // 如果是文件夾,就繼續深入遍歷 if (srcFile.isDirectory()) { File[] files = srcFile.listFiles(); for (File each : files) { iterateGetFiles(each); } } else if (srcFile.getAbsolutePath().endsWith(".avi")) { // 不是文件夾而且文件格式為avi,就將該文件添加到待命名文件的list集合中 RenameFiles.srcFiles.add(srcFile); } } // end method-iterateGetFiles}// end class-RenameFiles
part_4:重命名及移動后的效果:
E:/BaiduYun/張孝祥_Java多線程與并發庫
總結
以上就是本文關于java文件的重命名與移動操作實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
新聞熱點
疑難解答
圖片精選