Rename

file.rename(src,desc);如果src和desc的参数在同一个目录下,那么就会将文件重新写一遍或者是重新命名,如果不在同一个目录下,那么就会将文件从src目录剪切并复制到desc目录下。


package com.huawei.test;

import java.io.File;

/**
* 文件 批量重命名
*
* @author ruanqiang
*
*/
public class BatchRenameFile {
// 输出日志
public static volatile boolean isDebug = false;
private static int j = 0;

public static void main(String[] args) {
String root = "C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures";// 文件夹目录
File[] fs = new File(root).listFiles();

String newName = "picture";
System.out.println();
BatchRenameFile.isDebug = true;
try {
rename(fs, newName);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 批量 重命名 文件名
*
* @param files
* 文件列表(文件夹或文件)
* @param newName
* 新文件名
* @throws Exception
* 可能的异常
*/
public static void rename(File[] files, String newName) throws Exception {
if (files == null || newName == null || newName.trim().length() == 0) {
return;
}
for (int i = 0; i < files.length; i++) {
if (files[i] != null && files[i].exists()) {
File file = files[i];

int lastIndex = file.getAbsolutePath().lastIndexOf(File.separator);
// 父目录
String path = file.getAbsolutePath().substring(0, lastIndex + 1);
if (file.isFile()) {
// 文件,保持后缀名
String extensions = file.getName().lastIndexOf(".") > 0 ? (file
.getName().substring(file.getName().lastIndexOf(".")))
: "";
file.renameTo(new File(path + newName + j + extensions));
j++;
if (isDebug) {
System.out.println("文件[" + file.getName() + "],重命名为["
+ path + newName + j + extensions + "]");
}
} else {
// 改动处
File[] fs = new File(file.getAbsolutePath()).listFiles();
rename(fs, newName); //递归
}
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值