在Java中修改文件或目录名称可以通过多种方式实现,具体方法取决于需求场景。以下是常见的实现方式及代码示例:
一、修改文件名
1. 使用`File`类(基础方法)
适用于简单场景,代码量少且无需额外依赖。
```java
import java.io.File;
public class FileRenameDemo {
public static void main(String[] args) {
String folderPath = "D:/test";
File folder = new File(folderPath);
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
String oldName = file.getName();
String newName = "prefix_" + oldName;
File newFile = new File(folderPath + "/" + newName);
boolean success = file.renameTo(newFile);
System.out.println(success ? "重命名成功: " + newName : "重命名失败: " + oldName);
}
}
}
}
}
```
2. 使用`Files`工具类(推荐)
Java 7及以上版本推荐使用`java.nio.file.Files`类,支持异常处理和符号链接操作。
```java
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
public class BatchRename {
private String sourcePath;
private String prefix;
public BatchRename(String sourcePath, String prefix) {
this.sourcePath = sourcePath;
this.prefix = prefix;
}
public void rename() throws IOException {
Path dir = Paths.get(sourcePath);
if (!Files.exists(dir)) {
System.out.println("目录不存在");
return;
}
List .filter(Files::isRegularFile) .sorted(Comparator.comparing(Path::getFileName)); int count = 1; for (Path file : files) { String extension = file.getExtension(); Path newFile = dir.resolve(prefix + "_" + file.getFileName() + (extension.isEmpty() ? "" : "." + extension)); Files.move(file, newFile); System.out.println("重命名成功: " + newFile); } } public static void main(String[] args) { BatchRename batchRename = new BatchRename("D:/test", "prefix_"); try { batchRename.rename(); } catch (IOException e) { e.printStackTrace(); } } } ``` 二、修改包名和类名 1. 修改包名 使用IDE的重构功能(右键选择`Refactor` -> `Rename`)或手动修改`package`声明和导入语句。 2. 修改类名 同样通过IDE重构功能或手动修改文件名和导入语句。注意需要同步修改所有引用该类的地方。 三、注意事项 修改系统级文件(如计算机名)需管理员权限。 使用`Files`类时建议包裹在`try-catch`块中,避免程序崩溃。 `Files.move`方法可处理符号链接,而`File.renameTo`不支持。 通过以上方法,可根据具体需求选择合适的方式批量或单个修改文件/目录名称。权限问题:
异常处理:
符号链接: