Java實現(xiàn)本地文件批量重命名的示例代碼
更新時間:2023年10月23日 11:18:41 作者:來自宇宙的曹先生
本文主要介紹了Java實現(xiàn)本地文件批量重命名的示例代碼,主要步驟為獲取指定目錄下的所有文件,對每個文件進行修改,將修改后的文件名賦給該文件,具有一定的參考價值,感興趣的可以了解一下
1. 批量重命名
import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.stream.Stream; /** * @author 曹見朋 * @create 2023-10-23-10:02 */ public class FileBatchRename { public static void main(String[] args) { // 設置目錄路徑 String directoryPath = "D:/example"; // 構建文件路徑 Path directory = Paths.get(directoryPath); try { // 獲取目錄下的所有文件 Stream<Path> files = Files.list(directory); // 遍歷所有文件并重命名 files.forEach(file -> { try { // 獲取文件的名稱 String fileName = file.getFileName().toString(); // 新的文件名(可以按需修改) String newFileName = "new_" + fileName; // 構建新文件路徑 Path newFilePath = directory.resolve(newFileName); // 執(zhí)行文件重命名 Files.move(file, newFilePath, StandardCopyOption.REPLACE_EXISTING); System.out.println("Renamed: " + fileName + " to " + newFileName); } catch (IOException e) { e.printStackTrace(); } }); System.out.println("All files have been renamed."); } catch (IOException e) { e.printStackTrace(); } } }
在上述代碼中,我們首先指定了要重命名文件的目錄路徑。然后,我們使用NIO的Files.list()方法列出目錄中的所有文件,并遍歷這些文件。在遍歷的過程中,可以根據(jù)需要修改新的文件名,然后使用Files.move()方法執(zhí)行文件重命名操作。文件將被重命名為新的名稱,然后輸出重命名的結果。
2. 批量修改擴展名
package com.cjp.bio; import java.io.File; /** * @author 曹見朋 * @create 2023-10-23-9:02 */ public class BatchRenameFiles { public static void main(String[] args) { // 指定目錄路徑 String directoryPath = "D:/NIO/"; // 舊的文件擴展名 String oldExtension = ".html"; // 新的文件擴展名 String newExtension = ".txt"; // 獲取目錄下的所有文件 File directory = new File(directoryPath); File[] files = directory.listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(oldExtension)) { // 構建新文件名 String newName = file.getName().replace(oldExtension, newExtension); // 創(chuàng)建新文件對象 File newFile = new File(directoryPath + newName); // 重命名文件 if (file.renameTo(newFile)) { System.out.println("Renamed " + file.getName() + " to " + newName); } else { System.err.println("Error renaming " + file.getName()); } } } } else { System.err.println("Directory not found."); } } }
到此這篇關于Java實現(xiàn)本地文件批量重命名的示例代碼的文章就介紹到這了,更多相關Java 本地文件批量重命名內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決springboot的aop切面不起作用問題(失效的排查)
這篇文章主要介紹了解決springboot的aop切面不起作用問題(失效的排查),具有很好的參考價值,希望對大家有所幫助。 一起跟隨小編過來看看吧2020-04-04