本来想写一个界面批量写注释 批量给压缩包添加和删除文件,最近没时间了m,大概写了一下工具类,还没有简化,先记录下
package com.bdkjzx.winrar.util; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class BatUtil { private static List<File> fileList = new ArrayList<File>(); private static Runtime cmd = Runtime.getRuntime(); static String suffix = ".rar"; private static String winrarPath="D:/WinRAR/WinRAR.exe"; private static String isIbak=" -ibck ";//是否后台运行 private static String rate="-m1"; //压缩比率 -m0 存储 添加到压缩文件时不压缩文件。-m1 最快 -m2 较快 -m3 标准 -m4 较好 -m5 最好 public static void main(String[] args) { String commandStr = ""; String filePath = "F:/testwinrar2"; try { File root = new File(filePath); extractFiles(root); // compressFiles(root); } catch (Exception e) { e.printStackTrace(); } } static List<File> getFiles(File root) { File[] files = root.listFiles(); for (File childFile : files) { if (childFile.isDirectory()) { getFiles(childFile); } else { if (childFile.getName().endsWith(suffix)) { fileList.add(childFile); } } } return fileList; } /** * 批量添加文件 * * @param root * @return */ static boolean addFiles(File root) { File[] files = root.listFiles(); for (File childFile : files) { if (childFile.isDirectory()) { getFiles(childFile); } else { if (childFile.getName().endsWith(suffix)) { fileList.add(childFile); } } } return false; } /** * 批量解压文件 * * @param root * @return */ static void extractFiles(File root) { File[] files = root.listFiles(); String suffix = ".rar"; boolean flag = false; try { for (File childFile : files) { if (childFile.isDirectory()) { extractFiles(childFile); } else { if (childFile.getName().endsWith(suffix)) { String fPath = childFile.getAbsolutePath(); String path = childFile.getAbsolutePath() .substring(0, childFile.getAbsolutePath().lastIndexOf(".")).replace("/", "/"); String commandStr = " cmd.exe /c mkdir " + path; cmd.exec(commandStr); commandStr = winrarPath+" x -y -ep1 -dr "+isIbak+ fPath + " " + path; System.out.println(commandStr); cmd.exec(commandStr); } } } } catch (IOException e) { e.printStackTrace(); } } /** * 批量压缩文件 * * @param root * @return */ static boolean compressFiles(File root) { File[] files = root.listFiles(); try { for (File childFile : files) { if (childFile.isDirectory()) { String fPath = childFile.getAbsolutePath(); String commandStr = winrarPath+" a -s -ep1 -df -y "+isIbak + fPath + ".rar " + fPath; System.out.println(commandStr); cmd.exec(commandStr); } else { if(!childFile.getName().endsWith(suffix)){ String fPath = childFile.getAbsolutePath(); String path = childFile.getAbsolutePath() .substring(0, childFile.getAbsolutePath().lastIndexOf(".")).replace("/", "/"); String commandStr = winrarPath+" a -s -ep1 -df -y "+rate+" " +isIbak+ path + ".rar " + fPath; System.out.println(commandStr); cmd.exec(commandStr); } } } } catch (Exception e) { } return false; } }