需求介紹:
在電影天堂上下載了一批電影。但這些電影文件名都有一個比較長的前綴,非常不美觀。我想把這些前綴去掉。
編程思路:
通過觀察發現,名字前綴有兩種,一種是用[]括起來的一段文字,一種是[]括起來的文字加一個.。
步驟:
1,獲取所有電影名字
2,找出']'所在位置 ?public int indexOf(int ch)
3,判斷']'的下一位置是不是'.'
4,從']'或'.'的下一位置起復制字符串,public String substring(int beginIndex),得到新的名字
5,改名 使用File類的renameTo(File)方法
源代碼:
import java.io.*;
public class RenameMovie{
public static void main(String[] args){
File path = new File(".");
String[] list;
list = path.list();
for(int i = 0; i < list.length; i++)
{
?int newNameStart = list[i].indexOf(']');
if(newNameStart == -1)
continue;
if(list[i].charAt(newNameStart+1)=='.')
newNameStart++;
renameFile(".",list[i],list[i].substring(newNameStart+1));
}
}
//重命名文件
public static int renameFile(String path,String oldname,String newname) {
File oldfile = new File(path + "/" + oldname);
File newfile = new File(path + "/" + newname);
if(!oldname.equals(newname) && oldfile.exists() && (!newfile.exists()))
{
oldfile.renameTo(newfile);
return 0;
}
else
{
return -1;
}
}
}
最終效果:
以后再下載了電影再運行一遍就可以啦!耶!
***