Java實(shí)現(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) {
// 設(shè)置目錄路徑
String directoryPath = "D:/example";
// 構(gòu)建文件路徑
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;
// 構(gòu)建新文件路徑
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í)行文件重命名操作。文件將被重命名為新的名稱,然后輸出重命名的結(jié)果。
2. 批量修改擴(kuò)展名
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/";
// 舊的文件擴(kuò)展名
String oldExtension = ".html";
// 新的文件擴(kuò)展名
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)) {
// 構(gòu)建新文件名
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.");
}
}
}到此這篇關(guān)于Java實(shí)現(xiàn)本地文件批量重命名的示例代碼的文章就介紹到這了,更多相關(guān)Java 本地文件批量重命名內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Java語言MD5加密Base64轉(zhuǎn)換方法
這篇文章主要為大家詳細(xì)介紹了基于Java語言的MD5加密Base64轉(zhuǎn)換方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09
SpringBoot深入理解之內(nèi)置web容器及配置的總結(jié)
今天小編就為大家分享一篇關(guān)于SpringBoot深入理解之內(nèi)置web容器及配置的總結(jié),小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-03-03
解決springboot的aop切面不起作用問題(失效的排查)
這篇文章主要介紹了解決springboot的aop切面不起作用問題(失效的排查),具有很好的參考價(jià)值,希望對大家有所幫助。 一起跟隨小編過來看看吧2020-04-04
java并發(fā)包JUC誕生及詳細(xì)內(nèi)容
這篇文章主要為大家介紹了java并發(fā)包JUC的誕生及JUC增加的內(nèi)容詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-02-02
Java實(shí)現(xiàn)的決策樹算法完整實(shí)例
這篇文章主要介紹了Java實(shí)現(xiàn)的決策樹算法,簡單描述了決策樹的概念、原理,并結(jié)合完整實(shí)例形式分析了java實(shí)現(xiàn)決策樹算法的相關(guān)操作技巧,代碼中備有較為詳盡的注釋便于理解,需要的朋友可以參考下2017-11-11

