使用Java实现本地文件批量重命名

编程入门 行业动态 更新时间:2024-10-18 12:25:15

使用Java实现本地文件批量<a href=https://www.elefans.com/category/jswz/34/1756678.html style=重命名"/>

使用Java实现本地文件批量重命名

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);// 执行文件重命名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()方法列出目录中的所有文件,并遍历这些文件。在遍历的过程中,可以根据需要修改新的文件名,然后使用Files.move()方法执行文件重命名操作。文件将被重命名为新的名称,然后输出重命名的结果。

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);// 创建新文件对象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实现本地文件批量重命名

本文发布于:2023-12-04 20:07:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1662082.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重命名   文件批量   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!