一、前言
定义文件批量修改ModifyAllFile类,实现控制台输入的指定路径下的.java/.jsp/.xml后缀文件首行增加注释说明,详情参见代码示例。
二、代码示例
import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileOutputStream;@b@import java.io.IOException;@b@import java.io.InputStreamReader;@b@import java.io.LineNumberReader;@b@import java.util.ArrayList;@b@import java.util.Arrays;@b@import java.util.HashMap;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.Scanner;@b@import java.util.Set;@b@@b@/**@b@ * 修改所有文件(加注释),便于提测时提全量。@b@ */@b@@b@public class ModifyAllFile{@b@ @b@ /**@b@ * 支持多条规则(以;分隔,每条规则以|分隔后缀名和增加内容)(a|b|c表示以a或b后后缀的文件将在文件头增加c).@b@ */@b@ static String rule = ".java||////modify by xwood.net////;.jsp|.xml|<!-- modify by xwood.net-->;";@b@@b@ /**@b@ * 在末尾追加注释.@b@ */@b@ static List<String> appendInEnd = Arrays.asList(".xml");@b@@b@ private static String encode = "utf-8";@b@@b@ public static void main(String[] args) {@b@ System.out.println("请输入待修改的文件(夹)的绝对路径:");@b@ @SuppressWarnings("resource")@b@ Scanner scanner = new Scanner(System.in);@b@ String path = scanner.nextLine();@b@ modify(path, rule);@b@ }@b@@b@ /**@b@ * 文件首行增加内容.@b@ * @b@ * @param path@b@ * 待修改文件路径@b@ * @param rules@b@ * 修改规则@b@ */@b@ public static void modify(String path, String rules) {@b@ if (isNullOrEmpty(rules)) {@b@ System.out.println("规则为空...");@b@ return;@b@ }@b@ Map<String, String> mapRule = buildRuleMap(rules);@b@ List<String> files = null;@b@ if (null != mapRule && !mapRule.isEmpty()) {@b@ files = getAllFilePath(path, mapRule.keySet());@b@ }@b@ try {@b@ modifyFile(files, mapRule);@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ System.out.println("修改完成");@b@ }@b@@b@ /**@b@ * 构建规则Map.@b@ * @b@ * @param rules@b@ * 规则字符串@b@ * @return Map@b@ */@b@ private static Map<String, String> buildRuleMap(String rules) {@b@ Map<String, String> mapRule = new HashMap<String, String>();@b@ String[] arr = rules.split(";");@b@ for (String keyVal : arr) {@b@ if (!isNullOrEmpty(keyVal)) {@b@ String[] spl = keyVal.split("\\|");@b@ for (int i = 0; i < spl.length - 1; i++) {@b@ mapRule.put(spl[i], spl[spl.length - 1]);@b@ }@b@ }@b@ }@b@ mapRule.remove("");@b@ return mapRule;@b@ }@b@@b@ /**@b@ * 按规则修改特定文件.@b@ * @b@ * @throws Exception@b@ * @b@ */@b@ private static void modifyFile(List<String> filePaths, Map<String, String> mapRule) throws Exception {@b@ if (isNullOrEmpty(mapRule) || isNullOrEmpty(filePaths)) {@b@ return;@b@ }@b@ String addNote = "";@b@ String fileSuffix = "";@b@ for (String path : filePaths) {@b@ for (String suffix : mapRule.keySet()) {@b@ if (path.endsWith(suffix)) {@b@ fileSuffix = suffix;@b@ addNote = mapRule.get(suffix);@b@ break;@b@ }@b@ }@b@ FileInputStream inputStream = new FileInputStream(path);@b@ LineNumberReader reader = new LineNumberReader(new InputStreamReader(inputStream, encode));@b@ StringBuffer content = new StringBuffer();@b@ if (!appendInEnd.contains(fileSuffix)) {@b@ content.append(addNote);@b@ content.append("\r\n");@b@ }@b@ String s = reader.readLine();@b@ while (s != null && !"null".equals(s)) {@b@ content.append(s);@b@ content.append("\r\n");@b@ s = reader.readLine();@b@ }@b@ if (appendInEnd.contains(fileSuffix)) {@b@ content.append(addNote);@b@ }@b@ content.append("\r\n");@b@ reader.close();@b@ // try {@b@ // FileWriter fw = new FileWriter(path);@b@ // fw.write(content.toString());@b@ // fw.close();@b@ // } catch (IOException e) {@b@ // e.printStackTrace();@b@ // }@b@ writeStringToFile(path, content.toString(), encode);@b@ }@b@@b@ }@b@@b@ /**@b@ * 将字符串数据存于本地(FileUtil工具类).@b@ * @b@ * @param fileName@b@ * 文件名@b@ * @param data@b@ * 数据@b@ * @param encode@b@ * 编码(可为null)@b@ * @throws IOException@b@ * IO异常@b@ */@b@ private static void writeStringToFile(String fileName, String data, String encode) throws IOException {@b@ FileOutputStream output = null;@b@ File file = new File(fileName);@b@ if (file.exists()) {@b@ if (file.isDirectory())@b@ throw new IOException("File '" + file + "' exists but is a directory");@b@ if (!file.canWrite())@b@ throw new IOException("File '" + file + "' cannot be written to");@b@ } else {@b@ File parent = file.getParentFile();@b@ if (parent != null && !parent.exists() && !parent.mkdirs())@b@ throw new IOException("File '" + file + "' could not be created");@b@ }@b@ try {@b@ output = new FileOutputStream(file);@b@ if (data != null)@b@ if (encode == null)@b@ output.write(data.getBytes());@b@ else@b@ output.write(data.getBytes(encode));@b@ } finally {@b@ if (null != output) {@b@ try {@b@ output.close();@b@ } catch (IOException e) {@b@ System.out.print("");@b@ }@b@ }@b@ }@b@ }@b@@b@ /**@b@ * 所有待转换文件绝对路径.@b@ * @b@ * @param path@b@ * @return 所有带转换文件路径@b@ */@b@ private static List<String> getAllFilePath(String path, Set<String> suffixSet) {@b@ /**@b@ * 所有待转换文件绝对路径.@b@ */@b@ List<String> filePaths = new ArrayList<String>();@b@ File root = new File(path);@b@ File[] files = root.listFiles();@b@ if (files == null) {@b@ filePaths.add(path);@b@ return filePaths;@b@ }@b@ for (File file : files) {@b@ if (file.isDirectory()) {@b@ // 递归调用@b@ List<String> list = getAllFilePath(file.getAbsolutePath(), suffixSet);@b@ if (!isNullOrEmpty(list)) {@b@ filePaths.addAll(list);@b@ }@b@ // System.out.println(filePath + "目录下所有子目录及其文件" + file.getAbsolutePath());@b@ } else {@b@ // System.out.println(filePath + "目录下所有文件" + file.getAbsolutePath());@b@ for (String suf : suffixSet) {@b@ if (file.getAbsolutePath().endsWith(suf)) {@b@ filePaths.add(file.getAbsolutePath());@b@ }@b@ }@b@ }@b@ }@b@ return filePaths;@b@ }@b@@b@ /**@b@ * 是否为null或空字符串或空集合.@b@ * @b@ * @param param@b@ * 参数@b@ * @return bool@b@ */@b@ @SuppressWarnings("rawtypes")@b@ private static boolean isNullOrEmpty(Object param) {@b@ if (param instanceof String) {@b@ if (null == param || "".equals(((String) param).trim())) {@b@ return true;@b@ }@b@ } else if (param instanceof List) {@b@ if (null == param || ((List) param).isEmpty()) {@b@ return true;@b@ }@b@ } else if (param instanceof Map) {@b@ if (null == param || ((Map) param).isEmpty()) {@b@ return true;@b@ }@b@ }@b@ return false;@b@ }@b@@b@}