1.第一种方法(不够简单):
package com.jingxuan.renamefile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Scanner;
/*
*批量修改同一目录下的扩展名是.jpg的图片,生成的新图片的名字从文件中读取
*
*/
public class RenameFilesUtil {
public static void main(String[] args) throws Exception {
//图片文件所在目录
File file = new File("F:/抽奖系统/card");
//获取文件的对象
File[] files = file.listFiles();
//获奖名单文件路径
File f = new File("F:/抽奖系统/抽奖名单.txt");
Scanner sc = new Scanner(f);
//生成新图片的路径
File newPath =new File("F:\\抽奖系统\\newPic");
if(!newPath.exists())
newPath.mkdirs();
FileInputStream fis = null;
OutputStream fos = null;
for(File fe : files){
fis = new FileInputStream(fe);
fos = new FileOutputStream(newPath.getAbsolutePath() +"\\"+ sc.nextLine() + ".jpg");
//一次读取的字节
byte[] b = new byte[1024];
int hasRead = 0;
while((hasRead = fis.read(b)) != -1){
fos.write(b, 0, hasRead);
}
}
fis.close();
fos.close();
sc.close();
}
}
2.第二种方法(推荐):
package com.yaphets.system;
import java.io.File;
import java.util.Scanner;
public class TestSet {
public static void main(String[] args) throws Exception {
File f = new File("F:\\抽奖系统\\card");
File lucky = new File("F:\\抽奖系统\\抽奖名单.txt");
Scanner sc = new Scanner(lucky);
File[] files = f.listFiles();
for(File file : files){
file.renameTo(new File(f.getAbsolutePath() + File.separator + sc.nextLine() + ".jpg"));
}
sc.close();
}
}
3.小技巧:生成各个不相同的随机数
private static Set<Integer> random(){
Set<Integer> set = new HashSet<>();
while(set.size() < 3){
int r = (int)(Math.random() * 52);
set.add(Integer.valueOf(r));
}
return set;
}
原理:利用set集合的不可重复性
批量修改指定路径文件名
最新推荐文章于 2022-12-14 23:21:52 发布