Java changeFileName

package com.easyfun.juns;

import java.io.File;
import java.util.Scanner;

/***
 * 
 * class ChangeFileName used to handle change file name, name of automatic
 * sorting.Need to enter two parameters Parameters 1 used to represent the name
 * of the prefix, 2 used to modify the file path
 * 
 * @author juns
 * 
 * @time 2015-10-31
 */
public class ChangeFileName {

	public static String prefix;
	public static String filePathName;

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		prefix = scanner.next();
		filePathName = scanner.next();

		File file = new File(filePathName);
		if (file.exists()) {
			if (file.isDirectory()) {
				changeFolderName(file);
			} else {
				changeFileName(file, 0);
			}
		}

		scanner.close();
	}

	public static void changeFolderName(File file) {
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					changeFolderName(files[i]);
				} else {
					changeFileName(files[i], i);
				}
			}
		}
	}

	public static void changeFileName(File file, int i) {
		if (file.isFile()) {
			String oldName = file.getName();
			String suffix = "";

			if (oldName.lastIndexOf(".") >= 0)
				suffix = oldName.substring(oldName.lastIndexOf(".") + 1);
			if (oldName.indexOf(".") >= 0) {
				oldName = oldName.substring(0, oldName.indexOf("."));
			}

			i++;
			String newName = prefix + "_" + i + "." + suffix;
			String path = file.getParent();
			File newFile = new File(path + "/" + newName);

			file.renameTo(newFile);
		}
	}
}


用来修改本地文件或文件夹名称的工具类。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值