java 將指定擴展名的文件中unicode編碼 轉爲中文,將換行改爲linux換行符

package com.common.convert;

import cn.hutool.core.io.FileUtil;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.assertj.core.util.Lists;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.*;
/**
 * unicode 轉 中文
 * @author: ZhangHouYing
 * @date: 2020-05-28 16:48
 */
public class UnicodeToCn {

	public static List<String> getAllFiles(String folder,String ext){
		List<String> filePathList = Lists.newArrayList();
		File folderFile = new File(folder);
		File[] fileList = folderFile.listFiles();
		for (File file : fileList) {
			if (file.isFile()) {
				String fileAbsolutePath = file.getAbsolutePath();
				if (fileAbsolutePath.endsWith(ext)) {
					filePathList.add(fileAbsolutePath);
				}
			} else if(file.isDirectory()){
				filePathList.addAll(getAllFiles(file.getAbsolutePath(), ext));
			}
		}
		return filePathList;
	}

	/**
	 * @Title: unicodeDecode
	 * @Description: unicode解碼
	 * @param string
	 * @return
	 */
	public static String unicodeDecode(String string) {
		Pattern pattern = compile("(\\\\u(\\p{XDigit}{4}))");
		Matcher matcher = pattern.matcher(string);
		char ch;
		while (matcher.find()) {
			ch = (char) Integer.parseInt(matcher.group(2), 16);
			string = string.replace(matcher.group(1), ch + "");
		}
		return string;
	}

	public static void changeUnicodeToCn(String filePath) {
		try {
			List<String> result = Lists.newArrayList();
			File file = new File(filePath);
			List<String> lines = Files.readLines(file, Charsets.UTF_8);
			StringBuilder sb = new StringBuilder();
			lines.forEach(line->{
				sb.append(unicodeDecode(line)).append("\n");
			});
			FileUtil.writeBytes(sb.toString().getBytes(Charsets.UTF_8),file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args){
		String path = "D:\\work\\ycf\\gitee\\jeecg-boot";
		List<String> fileList = getAllFiles(path,".java");
		fileList.forEach(filePath->{
			changeUnicodeToCn(filePath);
		});
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章