1 1 import java.io.File; 2 2 import java.util.Scanner; 3 3 //批量替换文件名字符 4 4 public class Test07 { 5 6 public static void reName() { 6 7 ...
1 1 import java.io.File; 2 2 import java.util.Scanner; 3 3 //批量替换文件名字符 4 4 public class Test07 { 5 6 public static void reName() { 6 7 while (true) { 7 8 Scanner sc = new Scanner(System.in); 8 9 String filePath = "";// 输入路径 9 10 File file = new File("");// File对象10 11 String dirPath = null;// 绝对路径11 12 // isDirectory() 测试此抽象路径名表示的文件是否是一个目录12 13 while (!file.isDirectory()) {13 14 System.out.println("请输入你想要查看的文件夹(e:\\io)");14 15 filePath = sc.nextLine() + "\\";15 16 file = new File(filePath);16 17 // getAbsolutePath()返回此抽象路径名的绝对路径名形式。17 18 dirPath = file.getAbsolutePath();18 19 }19 20 System.out.println(dirPath);20 21 // 返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。21 22 File[] fileList = file.listFiles();22 23 System.out.println("您输入的路径下有文件如下:");23 24 for (File file2 : fileList) {//利用foreach循环体24 25 if (file2.isFile()) {//如果是文件,获得文件名,并输出25 26 String formFile = file2.getName();26 27 System.out.println(formFile);27 28 }28 29 }29 30 System.out.println("请输入你想要替换的旧字符:");30 31 String oldStr = sc.nextLine();31 32 System.out.println("请输入您想要替换的新字符:");32 33 String newStr = sc.nextLine();33 34 int count = 0;//声明一个int型的count,用于记录替换成功的文件数34 35 for (int i = 0; i < fileList.length; i++) {35 36 String name = fileList[i].getName();//得到每个文件的文件名36 37 name = name.replace(oldStr, newStr);//替换包含oldStr字符的文件名37 38 name = dirPath + "\\" + name;//文件名38 39 File toFile = new File(name);//把name转换为File对象39 40 if (fileList[i].exists() && !toFile.exists()) {//新文件不存在才能更改40 41 fileList[i].renameTo(toFile);//rename();File的方法,用户更名41 42 count++;//替换成功文件个数+142 43 }43 44 }44 45 System.out.println("替换成功,总文件数:" + fileList.length + ",成功" + count45 46 + "个,失败" + (fileList.length - count) + "个。");46 47 System.out.println("失败的文件为:");47 48 for (File file2 : fileList) {//输出没有替换成功的文件名48 49 if (file2.isFile()) {49 50 String formFile = file2.getName();50 51 System.out.println("\t"+formFile);51 52 }52 53 }53 54 sc.close();54 55 System.out.println("3秒后关闭");55 56 new Thread() {//新建一个线程,停留三秒后输出56 57 @Override57 58 public void run() {58 59 try {59 60 sleep(3000);60 61 } catch (InterruptedException e) {61 62 e.printStackTrace();62 63 }63 64 }64 65 }.start();65 66 break;66 67 }67 68 }68 69 public static void main(String[] args) {69 70 reName();70 71 }71 72 }72 73 73
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:批量替换文件字符
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。