在java中使用 File.renameTo(File)实现重命名.

Here is part of my files:

1 [北京圣思园Java培训教学视频]Java.SE.前9日学习成果测试题(2010年12月2日).rar 

2 [北京圣思园Java培训教学视频]Java.SE.第一百一十一讲.基于UDP的网络通信详解.rar 

3 [北京圣思园Java培训教学视频]Java.SE.第一百一十七讲.Java.SE项目迭代二深度详解之线程对象设计.rar 

4 [北京圣思园Java培训教学视频]Java.SE.第一百一十三讲.Java.SE项目迭代一.rar 

5 [北京圣思园Java培训教学视频]Java.SE.第一百一十九讲.Java.SE项目迭代二深度详解之系统交互.rar 

6 [北京圣思园Java培训教学视频]Java.SE.第一百一十二讲.基于UDP的网络通信详解.续.rar 

7 [北京圣思园Java培训教学视频]Java.SE.第一百一十五讲.Java.SE项目迭代一精讲.续.rar 
View Code

 

As you can image,if I gonna learn the courses course-to-course.I gonna find it difficult and boring to find each them,and the sort type is not what we want. So I have to rename the file as simple as possible.

Here is just  a segment code that demonstates how to use the  File.renameTo(File).

 1 public static void main(String[] args) {

 2         String path = "H:\\Java\\JavaSE\\";

 3         File root = new File(path);

 4         String oriName = "";

 5         String newName = "";

 6         String toClip = "[北京圣思园Java培训教学视频]Java.SE.";

 7         for (String f : root.list()) {

 8             File fSub = new File(path + f); //File to be rename(Must append from the root path).

 9             if (!fSub.isFile())    //Only operate File.

10                 continue;

11             if (fSub.getName().startsWith(toClip)) {

12                 oriName =fSub.getName();

13                 newName = oriName.substring(toClip.length());

14                 File fSubNew = new File(path + newName);    //The target File.

15                 if(fSub.renameTo(fSubNew))

16                     System.out.println(fSub.getAbsolutePath() + " rename successfully");

17                 else 

18                     System.out.println(fSub.getAbsolutePath() + " rename failed");

19             }

20         }

21     }
View Code

 

你可能感兴趣的:(java)