有時候網上下載一些學習視頻,文件上面有很長很長的廣告名字,廣告名遮擋了要瀏覽的真正內容,看着就煩人,所以我寫了一個文件批處理程序,將文件內所有符合條件的字符修改,刪除。
代碼如下:
package com.practice.method;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* 刪掉文件夾內所有自定義內容
* @author Lenkee
*
*/
public class 文件批處理 {
static int Counter=0;//用於計數文件夾中所有文件數量
static int made=0,premade=0;
public static void main(String arg[]) throws InterruptedException{
Scanner input = new Scanner(System.in);
System.out.print("請輸入修改文件夾/文件路徑:");
String url = input.next();
String url2 = url.replaceAll("\\\\","/");
File file = new File(url2);
if(!file.isDirectory()||file.isFile()){
System.out.println("未找到文件或文件夾!");
return;
}
System.out.print("您要修改的內容:");
String str = input.next();
System.out.println("輸入修改後內容:");
String str2= input.next();
System.out.println(url2);
tree(file);
System.out.println("請稍後..");
updateFiles(file, str,str2);
System.out.println(">");
System.out.println("修改成功!");
}
static void tree(File f){
File[] fa=f.listFiles();
for(int i=0;i<fa.length;i++){
Counter++;
if(fa[i].isDirectory()){
tree(fa[i]);
}
}
}
/**
* 遞歸刪除文件夾內指定字符串
* @param url 指定目錄
* @param str 刪除的內容
* @throws InterruptedException
*/
public static void updateFiles(File file,String str,String str2) throws InterruptedException{
//先修改文件名稱,再遞歸子文件
String name = file.getName();
file = rName(file, cutName(name, str,str2));
made++;
if(made==(premade+Counter/10)){
System.out.print("-");
Thread.sleep(20);
premade=made;
}
File[] childs = getChilds(file);
if(childs!=null){ //如果是目錄,繼續遞歸
for (File file2 : childs) {
updateFiles(file2, str,str2);
}
}
return;
}
/**
* 獲取子文件
* @param url
* @return
*/
public static File[] getChilds(File file){
//獲取文件夾的所有子文件
File[] files = null;
if(file.isDirectory()){
// System.out.println("------- "+file.getName()+" 是一個文件夾------");
files = file.listFiles();
// int i=1;
// for (File file2 : files) {
// System.out.print("他的子文件有: "+i++);
// System.out.print(file2.getName()+" -- ");
// }
// i=1;
// System.out.println();
}
return files;
}
/**
* 名字串截取
* @param name 原文件名
* @param str 要修改的文件名
* param str2 修改後的文件名
* @return
*/
public static String cutName(String name,String str,String str2){
if(name.contains(str)){
int start = name.indexOf(str); //截取開始位置
int end = start+str.length(); //截取結束位置
StringBuffer head = new StringBuffer(name.substring(0, start)); //前半部分
StringBuffer tail = new StringBuffer(name.substring(end, name.length())); //後 半部分
StringBuffer newName = head.append(str2).append(tail);
return newName.toString();
}
return name;
}
//將文件、文件夾重命名
public static File rName(File file ,String name){
File fileNew = new File(file.getParent()+"/"+name);
file.renameTo(fileNew);
// System.out.println("重命名後路徑:"+fileNew.getPath());
return fileNew;
}
}
最後變成這樣