批量修改指定路径文件名

 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集合的不可重复性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值