天天看点

【ThinkingInJava】57、批量修改文件的名字

/**
* 书本:《Thinking In Java》
* 功能:批量修改文件的名字
* 文件:Restaurant.java
* 时间:2015年5月9日09:20:13
* 作者:cutter_point
*/
package Lesson18IO;

import java.io.File;

public class ChangeName
{
	public void isDirOrNot(File file)
	{
		if(file.isDirectory())
		{
			File[] files1 = file.listFiles();
			for(int i = 0; i < files1.length; ++i)
			{
				this.isDirOrNot(files1[i]); 		//遍历所有的目录
			}
		}
		
		if(file.isFile())
		{
			//如果不是目录的话,那么我们就准备改名了
			this.change(file);
		}
	}
	
	public void change(File file)	//改名
	{
		String name = file.getName();		//得到这个文件名
		boolean b = name.endsWith("jsp");
		if(b)	//如果是以jsp结尾的
		{
			String parentDir = file.getParent();
			String fileName = parentDir + File.separator + name.substring(0, file.getName().indexOf(".")) + ".html";
			File newFile = new File(fileName);	//得到文件路径
			if(file.renameTo(newFile))
			{
				System.out.println(name + "  修改成功 " + fileName);
			}
			else
			{
				System.out.println(name + "  修改失败 " + fileName);
			}
		}
	}
	
	public static void main(String[] args) throws Exception
	{
		File file = new File("C:/Users/feng/Desktop/小型电子商务/struts2_hibernate_bookstore700/WebRoot");
		ChangeName cn = new ChangeName();
		cn.isDirOrNot(file);
	}

}


           

路径自己可以改,效果我就不展示了,因为我的那个文件已经被我删了!!!

所以运行是没有结果的。