Java 对指定后缀文件批量转码

    xiaoxiao2022-07-07  203

    需求:对李刚老师的 轻量级Java EE企业应用实战(第5版),的代码批量进行转码( GBK->UTF-8 ),并且去掉代码前面的声明,然后对代码格式进行缩进。

    /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2018, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class ProcessArray { // 定义一个each()方法,用于处理数组, public void each(int[] target , Command cmd) { cmd.process(target); } }

    变成

    public class ProcessArray{ // 定义一个each()方法,用于处理数组, public void each(int[] target , Command cmd{ cmd.process(target); } }

     


    手动指定转换方向,指定转换文件

    public class TransformCodingDemo { private static String NEW_LINE = System.getProperty("line.separator"); private static int successCount = 0; private static int errorCount = 0; public static void main(String[] args) throws IOException { String path = "F:\\Procedure\\JAVA\\Frame\\代码\\Java"; File file = new File(path); getAllCatalog(file); System.out.println("成功转码\t:"+successCount); System.out.println("失败转码\t:"+errorCount); } /** * 递归遍历文件 */ public static void getAllCatalog(File file) throws IOException { File[] arrFiles = file.listFiles(); for (int i = 0; i < arrFiles.length; i++) { if (arrFiles[i].isDirectory()) { //是文件就递归 getAllCatalog(arrFiles[i]); } else { File tempFile = arrFiles[i]; if (tempFile.getName().endsWith(".java")) { try { encodeConvert(tempFile, "GBK", "UTF-8"); successCount++; } catch (Exception e) { e.printStackTrace(); System.out.println("失败文件:\t"+tempFile.getAbsolutePath()); errorCount++; } } } } } /** * 转码 * * @param file * @param convert 转码之前的编码 * @param target 转码之后的编码 * @throws IOException */ public static void encodeConvert(File file, String convert, String target) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), convert)); StringBuilder content = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { content.append(line); content.append(NEW_LINE); } //System.out.println(content.toString()); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), target)); bufferedWriter.write(content.toString()); bufferedWriter.close(); } } public class TransformCodingDemo2 { private static String NEW_LINE = System.getProperty("line.separator"); private static int successCount = 0; private static int errorCount = 0; public static void main(String[] args) throws IOException { String path = "F:\\Procedure\\JAVA\\Frame\\代码\\Java"; getAllCatalog(path); System.out.println("成功转码\t:"+successCount); System.out.println("失败转码\t:"+errorCount); } public static void getAllCatalog(String path) throws IOException { // 遍历g:\publish\codes\15目录下的所有文件和子目录 Files.walkFileTree(Paths.get(path) , new SimpleFileVisitor<Path>() { // 访问文件时候触发该方法 @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".java")) { File tempFile = new File(file.toString()); try { encodeConvert(new File(file.toString()), "GBK", "UTF-8"); successCount++; } catch (Exception e) { e.printStackTrace(); System.out.println("失败文件:\t"+tempFile.getAbsolutePath()); errorCount++; } } return FileVisitResult.CONTINUE; } }); } /** * 转码 * * @param file * @param convert 转码之前的编码 * @param target 转码之后的编码 * @throws IOException */ public static void encodeConvert(File file, String convert, String target) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), convert)); StringBuilder content = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { content.append(line); content.append(NEW_LINE); } System.out.println(content.toString()); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), target)); bufferedWriter.write(content.toString()); bufferedWriter.close(); } }

     


    递归遍历文件夹

    使用Files里面的方法

    @Test public void test() throws IOException { // 遍历g:\publish\codes\15目录下的所有文件和子目录 Files.walkFileTree(Paths.get("d:", "publish", "codes", "15") , new SimpleFileVisitor<Path>() { // 访问文件时候触发该方法 @Override public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException { System.out.println("正在访问" + file + "文件"); // 找到了FileInputStreamTest.java文件 if (file.endsWith("FileInputStreamTest.java")) { System.out.println("--已经找到目标文件--"); return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } // 开始访问目录时触发该方法 @Override public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException { System.out.println("正在访问:" + dir + " 路径"); return FileVisitResult.CONTINUE; } }); }

    使用File里面的方法 

    @Test public void test02() { getAllCatalog(new File("F:\\Procedure\\JAVA")); } public void getAllCatalog(File file) { File[] arrFiles = file.listFiles(); for(int i = 0; i < arrFiles.length; i++) { if(arrFiles[i].isDirectory()) { //是文件就递归 getAllCatalog(arrFiles[i]); }else { System.out.println(arrFiles[i].getAbsolutePath()); } } }

    打印出层级结构

    private static int countFiles = 0; private static int Directory = 0; @Test public void test() { File file = new File("F:\\Procedure\\JAVA\\"); getAllCatalog(file,0); System.out.println("文件个数:"+countFiles); System.out.println("文件夹个数:"+Directory); } public static void getAllCatalog(File file,int depthLegth) { depthLegth++; System.out.println(show(depthLegth)+file.getName()); File[] arrFiles = file.listFiles(); for(int i = 0; i < arrFiles.length; i++) { if(arrFiles[i].isDirectory()) { //是文件就递归 Directory++; getAllCatalog(arrFiles[i],depthLegth); }else { countFiles++; System.out.println(show(depthLegth+1)+arrFiles[i].getName()); } } } private static String show(int len) { StringBuffer str = new StringBuffer(); str.append("|"); for(int i = 0; i < len; i++) { str.insert(0,"--"); } str.insert(0,"|"); return str.toString(); }

    删除疯狂系列代码的声明部分

    如下

    /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2018, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2018, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class ProcessArray { // 定义一个each()方法,用于处理数组, public void each(int[] target , Command cmd) { cmd.process(target); } }

    使用正则替换掉即可

    private static String replace(String str) { // String replaceAll = str.replaceAll("/\\*[\\s\\S]*疯狂Java联盟[\\s\\S]*\\*/", "-"); String temp = "<br/>网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a>"; String replaceAll = str.replaceAll("/\\*[\\s\\S]*" + temp + "[\\s\\S]*\\*/", ""); return replaceAll; } private static String NEW_LINE = System.getProperty("line.separator"); private static int successCount = 0; private static int errorCount = 0; @Test public void test() throws IOException { String path = "F:\\Procedure\\JAVA\\Frame\\代码\\Spring"; File file = new File(path); getAllCatalog(file); System.out.println("成功替换\t:" + successCount); System.out.println("失败替换\t:" + errorCount); } /** * 递归遍历文件 */ public static void getAllCatalog(File file) throws IOException { File[] arrFiles = file.listFiles(); for (int i = 0; i < arrFiles.length; i++) { if (arrFiles[i].isDirectory()) { //是文件就递归 getAllCatalog(arrFiles[i]); } else { File tempFile = arrFiles[i]; if (tempFile.getName().endsWith(".java")) { try { convert(tempFile, StandardCharsets.UTF_8.toString()); successCount++; } catch (Exception e) { e.printStackTrace(); System.out.println("失败文件:\t" + tempFile.getAbsolutePath()); errorCount++; } } } } } /** * 替换掉下面的 */ /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2018, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ private static String replace(String str) { // String replaceAll = str.replaceAll("/\\*[\\s\\S]*疯狂Java联盟[\\s\\S]*\\*/", "-"); String temp = "<br/>网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a>"; String replaceAll = str.replaceAll("/\\*[\\s\\S]*" + temp + "[\\s\\S]*\\*/", ""); return replaceAll; } /** * @param file 文件 * @param code 文件的编码格式 */ public static void convert(File file, String code) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), code)); StringBuilder content = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { content.append(line); content.append(NEW_LINE); } System.out.println("-------------start-----------------"); System.out.println(content.toString()); String replaceStr = replace(content.toString()); System.out.println(replaceStr); System.out.println("--------------end----------------"); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), code)); bufferedWriter.write(replaceStr); bufferedWriter.close(); }

    代码格式缩进

    public class ProcessArray { // 定义一个each()方法,用于处理数组, public void each(int[] target , Command cmd) { cmd.process(target); } }

    变为 

    public class ProcessArray{ // 定义一个each()方法,用于处理数组, public void each(int[] target , Command cmd){ cmd.process(target); } }

    注意 

    public class ProcessArray// 定义一个each()方法,用于处理数组, { public void each(int[] target , Command cmd) { cmd.process(target); } } // 变为 public class ProcessArray// 定义一个each()方法,用于处理数组, { public void each(int[] target , Command cmd){ cmd.process(target); } } /** * 找出每一个切割的,并且缩进代码,返回缩进后的代码 */ private String codeIndentation(String str) { TreeMap<Integer, Integer> treeMap = new TreeMap<>();//用来存储切割点 int left = 0; int right; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '{') { right = i; left = i - 1; while (str.charAt(left) == ' ' || str.charAt(left) == '\n' || str.charAt(left) == '\r' || str.charAt(left) == '\t') { left--; } if (panduan(str.charAt(left))) {//tempstr.charAt(left) == ')' treeMap.put(left, right); } } } // System.out.println(treeMap); return connectStr(treeMap, str); } /** * 拼接字符串 * ========key value-------------key value-------------key value========= * ======== 是手动拼接的 * 然后在拼接没一个 value-------------key */ private String connectStr(TreeMap<Integer, Integer> treeMap, String str) { Set<Integer> keySet = treeMap.keySet(); ArrayList<Integer> arrayList = new ArrayList<>(keySet); String tempStr = str.substring(0, arrayList.get(0) + 1); for (int i = 0; i < arrayList.size() - 1; i++) { tempStr += str.substring(treeMap.get(arrayList.get(i)), arrayList.get(i + 1)+1); } tempStr += str.substring(treeMap.get(arrayList.get(arrayList.size()-1))); //System.out.println(tempStr); return tempStr; } /** * 排除 * public class ProcessArray//注释 * { */ private boolean panduan(char indexChar) { if ((indexChar == ')') || (indexChar >= 'a' && indexChar <= 'z' || indexChar >= 'A' && indexChar <= 'Z')) { return true; } return false; }

    只需要在前面的代码里面在添加一个即可

    System.out.println("-------------start-----------------"); System.out.println(content.toString()); String replaceStr = replace(content.toString()); replaceStr = codeIndentation(replaceStr);//代码缩进 System.out.println(replaceStr); System.out.println("--------------end----------------");

    完整代码 

    public class replaceDemo { private static String NEW_LINE = System.getProperty("line.separator"); private static int successCount = 0; private static int errorCount = 0; @Test public void test() throws IOException { String path = "F:\\Procedure\\JAVA\\Frame\\代码\\Spring"; File file = new File(path); getAllCatalog(file); System.out.println("成功替换,并缩进代码\t:" + successCount); System.out.println("失败替换,并缩进代码\t:" + errorCount); } /** * 递归遍历文件 */ public static void getAllCatalog(File file) throws IOException { File[] arrFiles = file.listFiles(); for (int i = 0; i < arrFiles.length; i++) { if (arrFiles[i].isDirectory()) { //是文件就递归 getAllCatalog(arrFiles[i]); } else { File tempFile = arrFiles[i]; if (tempFile.getName().endsWith(".java")) { try { convert(tempFile, StandardCharsets.UTF_8.toString()); successCount++; } catch (Exception e) { e.printStackTrace(); System.out.println("失败文件:\t" + tempFile.getAbsolutePath()); errorCount++; } } } } } /** * 替换掉下面的 */ /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2018, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ private static String replace(String str) { // String replaceAll = str.replaceAll("/\\*[\\s\\S]*疯狂Java联盟[\\s\\S]*\\*/", "-"); String temp = "<br/>网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a>"; String replaceAll = str.replaceAll("/\\*[\\s\\S]*" + temp + "[\\s\\S]*\\*/", ""); return replaceAll; } /** * @param file 文件 * @param code 文件的编码格式 */ public static void convert(File file, String code) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), code)); StringBuilder content = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { content.append(line); content.append(NEW_LINE); } System.out.println("-------------start-----------------"); System.out.println(content.toString()); String replaceStr = replace(content.toString()); replaceStr = codeIndentation(replaceStr);//代码缩进 System.out.println(replaceStr); System.out.println("--------------end----------------"); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), code)); bufferedWriter.write(replaceStr); bufferedWriter.close(); } /** * 找出每一个切割的,并且缩进代码,返回缩进后的代码 */ private static String codeIndentation(String str) { TreeMap<Integer, Integer> treeMap = new TreeMap<>();//用来存储切割点 int left = 0; int right; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '{') { right = i; left = i - 1; while (str.charAt(left) == ' ' || str.charAt(left) == '\n' || str.charAt(left) == '\r' || str.charAt(left) == '\t') { left--; } if (panduan(str.charAt(left))) {//tempstr.charAt(left) == ')' treeMap.put(left, right); } } } // System.out.println(treeMap); return connectStr(treeMap, str); } /** * 拼接字符串 * ========key value-------------key value-------------key value========= * ======== 是手动拼接的 * 然后在拼接没一个 value-------------key */ private static String connectStr(TreeMap<Integer, Integer> treeMap, String str) { Set<Integer> keySet = treeMap.keySet(); ArrayList<Integer> arrayList = new ArrayList<>(keySet); String tempStr = str.substring(0, arrayList.get(0) + 1); for (int i = 0; i < arrayList.size() - 1; i++) { tempStr += str.substring(treeMap.get(arrayList.get(i)), arrayList.get(i + 1)+1); } tempStr += str.substring(treeMap.get(arrayList.get(arrayList.size()-1))); //System.out.println(tempStr); return tempStr; } /** * 排除 * public class ProcessArray//注释 * { */ private static boolean panduan(char indexChar) { if ((indexChar == ')') || (indexChar >= 'a' && indexChar <= 'z' || indexChar >= 'A' && indexChar <= 'Z')) { return true; } return false; } }

     

    最新回复(0)