xls,xlxs的读取与写入

package com.shine.eiuop.utils.Utils2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.eclipse.jdt.internal.compiler.ast.EqualExpression;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
* title: 将汉字替换成英文(直接根据文档的明确的文件路径去替换)
*
* @author Administrator
* @时间 2009-7-30:下午09:28:10
*/
public class FileTransEnglishFromChinaesUtils2 {

/**去重后的文件中的替换的文件绝对路径 */
public static String rootDir = "D:\\SHINE_ROOT\\mspChinese纯路径(最终版).csv";

public static StringBuilder finalAll = new StringBuilder();

public static void main(String args[]) throws Exception {
dofind();
}

public static void dofind() throws Exception {

try{
//列出要替换的文件
String fileUrlLists = fileUrlList(rootDir);
String[] stringArrStrings = fileUrlLists.toString().split("\\r\\n");


//翻译好的文件
String transFile = "D:\\SHINE_ROOT\\mspChinese_译文.xlsx";
//返回译文的数据:[{指令=}{付款待办=}, {收款结果查询=}, {主动发起划款=}]
List<Map<String, String>> retList = readExcel(transFile);
String cellFirst = "";
String cellSecond = "";
for (int i = 0; i < retList.size(); i++) {
System.out.println("第"+i+"行:"+retList.get(i));
for (Entry<String, String> entry : retList.get(i).entrySet()){
cellFirst = entry.getKey();
cellSecond = entry.getValue();
}

for (int fileNum = 0; fileNum < stringArrStrings.length; fileNum++) {
//遍历所有文件,找到指定的文件
System.out.println(stringArrStrings[fileNum]);
if ("".equals(cellFirst)==true||"".equals(cellSecond)==true) {
continue;
}
deepDir(cellFirst,cellSecond,stringArrStrings[fileNum].replaceAll("/", "\\\\"));
}
}

}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalAll.setLength(0);
}

public static List<Map<String, String>> readExcel(String path) {
List<Map<String, String>> retList = new ArrayList<Map<String, String>>();
File file = new File(path);
FileInputStream fis = null;
Workbook workBook = null;
if (file.exists()) {
try {
fis = new FileInputStream(file);
workBook = WorkbookFactory.create(fis);
int numberOfSheets = workBook.getNumberOfSheets();
// sheet工作表
for (int s = 0; s < numberOfSheets; s++) {
Sheet sheetAt = workBook.getSheetAt(s);
// 获取工作表名称
String sheetName = sheetAt.getSheetName();
// 获取当前Sheet的总行数
int rowsOfSheet = sheetAt.getPhysicalNumberOfRows();
// 第一行
Row row0 = sheetAt.getRow(0);
int physicalNumberOfCells = sheetAt.getRow(0).getPhysicalNumberOfCells();
String[] title = new String[physicalNumberOfCells];
for (int i = 0; i < physicalNumberOfCells; i++) {
title[i] = row0.getCell(i).getStringCellValue();
}
Integer totalCells = title.length;
for (int r = 1; r < rowsOfSheet; r++) {
Row row = sheetAt.getRow(r);
if (row == null) {
continue;
}
Map<String, String> rowMap = new HashMap<String, String>();
int rowNum = row.getRowNum() + 1;
System.out.println("当前行:" + rowNum);
/** 循环Excel的列 */
Cell cell0 = row.getCell(0);
String cellValue = "";
if (null != cell0) {
// 以下是判断数据的类型
switch (cell0.getCellType()) {
case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell0.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell0.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell0.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = cell0.getStringCellValue();
break;
}
}
Cell cell1 = row.getCell(1);
String cell1Value = "";
if (null != cell1) {
// 以下是判断数据的类型
switch (cell1.getCellType()) {
case HSSFCell.CELL_TYPE_STRING: // 字符串
cell1Value = cell1.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cell1Value = cell1.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
cell1Value = cell1.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
cell1Value = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
cell1Value = "非法字符";
break;
default:
cell1Value = cell1.getStringCellValue();
break;
}
}
rowMap.put(cellValue, cell1Value);
retList.add(rowMap);
}
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("文件不存在!");
}
return retList;
}

/**
* 遍历所有文件,找到指定的jsp文件
* @param cellFirst 每一行的汉字
* @param cellSecond 每一行的英文
* @param rootDir 所有的文件
* @param fileRoot 指定的文件
* @return
* @throws Exception
*/
public static void deepDir(String cellFirst,String cellSecond,String fileRoot) throws Exception {
File folder = new File(fileRoot);
if (folder.getPath().endsWith(fileRoot)) {
writeComment(cellFirst,cellSecond,folder.getPath(),fileRoot);
}
}

/**
* 一行行遍历。找到标配的js文件,和include的所有jsp文件
* @param cellFirst 每一行的汉字
* @param cellSecond 每一行的英文
* @param filePathAndName
* @param fileName
* @return
* @throws Exception
*/
@SuppressWarnings("resource")
public static void writeComment(String cellChinaeseFirst,String cellEnglishSecond,String filePathAndName,String fileName)
throws Exception {
if (filePathAndName.endsWith(".jsp")) {
//存放查出来的jsp文件
List<String> allFileStrings = new ArrayList<String>();
//存放自己的js文件,当做标配
List<String> allJsFile = new ArrayList<String>();
allJsFile.add(fileName.split("\\.")[0]+".js");

StringBuffer buffer = new StringBuffer();
String line = null; // 用来保存每行读取的内容
InputStream is = new FileInputStream(filePathAndName);
BufferedReader reader = null;
if (filePathAndName.endsWith(".java")) {
reader = new BufferedReader(new InputStreamReader(is,"GBK"));
}else {
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
}

try {
line = reader.readLine();
//将每一行的汉字替换成英文
if (line!=null) {
//如果是注释或者@logMethod这样的就不翻译
Boolean isTrueBoolean = isValite(line);
if (isTrueBoolean == false) {
StringBuilder tmSr = new StringBuilder();
tmSr.append(deepMatcher(line));
if (!"".equals(tmSr.toString())) {
String[] stringsTStrings = tmSr.toString().split("\r\n");
for (int i = 0; i < stringsTStrings.length; i++) {
if (cellChinaeseFirst.equals(stringsTStrings[i].trim())) {
//if (!"getEnOrCnMsg(\"".equals(line.substring(line.indexOf(stringsTStrings[i].trim())-14, line.indexOf(stringsTStrings[i].trim())))) {
line = line.replace(cellChinaeseFirst, cellEnglishSecond);
//}
}
}
}
}
if (line.contains("/pages/")) {
line = line.replace("/pages/", "/enpages/");
}
if (line.contains("/pubpages/")) {
line = line.replace("/pubpages/", "/enpubpages/");
}
//要求划款日期在config.js公共类,需要特殊处理
// window.defaultText = {
// reqFtDateName : '要求划款日期'
// };
// window.defaultEnText = {
// reqFtDateName : 'Required payment date'
// };
if (line.contains("window.defaultText.reqFtDateName")) {
line = line.replace("window.defaultText.reqFtDateName", "window.defaultEnText.reqFtDateName");
}
//将service改成en的
// CURR_PAGE_SERVICE = 'TransferQueryWbPageService';改成CURR_PAGE_SERVICE = 'TransferQueryWbEnPageService'
//methodsMap.put("TaTradePublicService", "TaTradePublicService.getTradeDetailInfo");
String serviceMane = "";
String serviceFinalName = "";
if ( line != null && line.matches("(.*)Service\"(.*)")) {
if (line.contains("EnPageService")!=true && line.contains("EnService")!=true) {
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf("\"")+1,line.indexOf("Service\"")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}
}else if ( line != null && line.matches("(.*)Service\'(.*)")) {
if (line.contains("EnPageService")!=true && line.contains("EnService")!=true) {
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf("\'")+1,line.indexOf("Service\'")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("\r\n"); // 添加换行符
try {
line = reader.readLine();
//将每一行的汉字替换成英文(有可能一行存在多个汉字词语,所有需要拆分后替换
if (line!=null) {
//如果是注释或者@logMethod这样的就不翻译
Boolean isTrueBoolean = isValite(line);
if (isTrueBoolean == false) {
StringBuilder tmSr = new StringBuilder();
tmSr.append(deepMatcher(line));
if (!"".equals(tmSr.toString())) {
String[] stringsTStrings = tmSr.toString().split("\r\n");
for (int i = 0; i < stringsTStrings.length; i++) {
if (cellChinaeseFirst.equals(stringsTStrings[i].trim())) {
//if (!"getEnOrCnMsg(\"".equals(line.substring(line.indexOf(stringsTStrings[i].trim())-14, line.indexOf(stringsTStrings[i].trim())))) {
line = line.replace(cellChinaeseFirst, cellEnglishSecond);
//}
}
}
}
}
if (line.contains("/pages/")) {
line = line.replace("/pages/", "/enpages/");
}
if (line.contains("/pubpages/")) {
line = line.replace("/pubpages/", "/enpubpages/");
}

//要求划款日期在config.js公共类,需要特殊处理
// window.defaultText = {
// reqFtDateName : '要求划款日期'
// };
// window.defaultEnText = {
// reqFtDateName : 'Required payment date'
// };
if (line.contains("window.defaultText.reqFtDateName")) {
line = line.replace("window.defaultText.reqFtDateName", "window.defaultEnText.reqFtDateName");
}

//将service改成en的
// CURR_PAGE_SERVICE = 'TransferQueryWbPageService';改成CURR_PAGE_SERVICE = 'TransferQueryWbEnPageService'
//methodsMap.put("TaTradePublicService", "TaTradePublicService.getTradeDetailInfo");
String serviceMane = "";
String serviceFinalName = "";
if ( line != null && line.matches("(.*)Service\"(.*)")) {
if (line.contains("EnPageService")!=true && line.contains("EnService")!=true) {
serviceMane = (line.substring(line.indexOf("\"")+1,line.indexOf("Service\"")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}
}else if ( line != null && line.matches("(.*)Service\'(.*)")) {
if (line.contains("EnPageService")!=true && line.contains("EnService")!=true) {
serviceMane = (line.substring(line.indexOf("\'")+1,line.indexOf("Service\'")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} // 读取下一行
}
buffer.append("\r\n"); // 添加换行符
String filecontent = buffer.toString().trim();
// 再输出到原文件
try {
File f = new File(filePathAndName);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream out = new FileOutputStream(filePathAndName);
byte[] bytes = null;
if (filePathAndName.endsWith(".java")) {
bytes = filecontent.getBytes("GBK");
}else {
bytes = filecontent.getBytes("utf-8");
}
out.write(bytes);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}else if (filePathAndName.endsWith(".js")) {
// tmSr.append(filePathAndName);
// tmSr.append("\r\n"); // 添加换行符
//存放查出来的ServiceImpl文件
// if (filePathAndName.endsWith("TaTradeNontradingtransfer.js")) {
// System.out.println("1");
// }
List<String> allServiceFileStrings = new ArrayList<String>();
StringBuffer buffer = new StringBuffer();
String line = null; // 用来保存每行读取的内容
InputStream is = new FileInputStream(filePathAndName);
BufferedReader reader = null;
if (filePathAndName.endsWith(".java")) {
reader = new BufferedReader(new InputStreamReader(is,"GBK"));
}else {
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
}
try {
line = reader.readLine();
//将每一行的汉字替换成英文
if (line!=null) {
//如果是注释或者@logMethod这样的就不翻译
Boolean isTrueBoolean = isValite(line);
if (isTrueBoolean == false) {
StringBuilder tmSr = new StringBuilder();
tmSr.append(deepMatcher(line));
if (!"".equals(tmSr.toString())) {
String[] stringsTStrings = tmSr.toString().split("\r\n");
for (int i = 0; i < stringsTStrings.length; i++) {
if (cellChinaeseFirst.equals(stringsTStrings[i].trim())) {
//if (!"getEnOrCnMsg(\"".equals(line.substring(line.indexOf(stringsTStrings[i].trim())-14, line.indexOf(stringsTStrings[i].trim())))) {
line = line.replace(cellChinaeseFirst, cellEnglishSecond);
//}
}
}
}
}
if (line.contains("/pages/")) {
line = line.replace("/pages/", "/enpages/");
}
if (line.contains("/pubpages/")) {
line = line.replace("/pubpages/", "/enpubpages/");
}
//要求划款日期在config.js公共类,需要特殊处理
// window.defaultText = {
// reqFtDateName : '要求划款日期'
// };
// window.defaultEnText = {
// reqFtDateName : 'Required payment date'
// };
if (line.contains("window.defaultText.reqFtDateName")) {
line = line.replace("window.defaultText.reqFtDateName", "window.defaultEnText.reqFtDateName");
}
}
} catch (IOException e) {
e.printStackTrace();
} // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("\r\n"); // 添加换行符
try {
line = reader.readLine();

//将每一行的汉字替换成英文
if (line!=null) {
//如果是注释或者@logMethod这样的就不翻译
Boolean isTrueBoolean = isValite(line);
if (isTrueBoolean == false) {
StringBuilder tmSr = new StringBuilder();
tmSr.append(deepMatcher(line));
if (!"".equals(tmSr.toString())) {
String[] stringsTStrings = tmSr.toString().split("\r\n");
for (int i = 0; i < stringsTStrings.length; i++) {
if (cellChinaeseFirst.equals(stringsTStrings[i].trim())) {
//if (!"getEnOrCnMsg(\"".equals(line.substring(line.indexOf(stringsTStrings[i].trim())-14, line.indexOf(stringsTStrings[i].trim())))) {
line = line.replace(cellChinaeseFirst, cellEnglishSecond);
//}
}
}
}
}
if (line.contains("/pages/")) {
line = line.replace("/pages/", "/enpages/");
}
if (line.contains("/pubpages/")) {
line = line.replace("/pubpages/", "/enpubpages/");
}
//要求划款日期在config.js公共类,需要特殊处理
// window.defaultText = {
// reqFtDateName : '要求划款日期'
// };
// window.defaultEnText = {
// reqFtDateName : 'Required payment date'
// };
if (line.contains("window.defaultText.reqFtDateName")) {
line = line.replace("window.defaultText.reqFtDateName", "window.defaultEnText.reqFtDateName");
}

String serviceMane = "";
String serviceFinalName = "";
if ( line != null && line.matches("(.*)Service\"(.*)")) {
if (line.contains("EnPageService")!=true && line.contains("EnService")!=true) {
// if('38080504' == menuCode){
// return "MsgManagementXpdocfilePageService";
// }else if('38080505' == menuCode){
// return "MsgManagementZjdocfilePageService";
// }else if('38150220' == menuCode){
// return "RptcenterTarptTarptdownloadPageService";
//这边会有上面的情况;返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1
if (line.indexOf("\'")==-1 && line.indexOf("\"")!=-1 ) {//不是单引号.是双引号
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf("\"")+1,line.indexOf("Service\"")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}else if(line.indexOf("\'")!=-1 && line.indexOf("\"")==-1 ){//不是双引号.是单引号 QUERY_BANK_ACC_LIST : "TransferApplyTawbPageService
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf("\'")+1,line.indexOf("Service\'")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}else {
continue;
}
}
}else if ( line != null && line.matches("(.*)Service\'(.*)")) {
if (line.contains("EnPageService")!=true && line.contains("EnService")!=true) {
// if('38080504' == menuCode){
// return 'MsgManagementXpdocfilePageService';
// }else if('38080505' == menuCode){
// return 'MsgManagementZjdocfilePageService';
// }else if('38150220' == menuCode){
// return 'RptcenterTarptTarptdownloadPageService';
//这边会有上面的情况;返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1
if (line.indexOf("\'")==-1 && line.indexOf("\"")!=-1 ) {//不是单引号.是双引号
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf("\"")+1,line.indexOf("Service\"")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}else if(line.indexOf("\'")!=-1 && line.indexOf("\"")==-1 ){//不是双引号.是单引号
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf("\'")+1,line.indexOf("Service\'")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}else {
continue;
}
}
} else if ( line != null && line.matches("(.*)Service\\.(.*)")) {
if (line.contains("EnPageService")!=true && line.contains("EnService")!=true) {
//$("#detail_serviceUrl").val("TaTradePublicService.getTradeDetailInfo");特殊处理
if (line.contains(".val(\"")) {
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf(".val(\"")+5,line.indexOf("Service.")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
continue;
}
// pb.im.send.Methods = {
// QUERY_DETAIL:'InfoSendService.getMsgInfoDetailDTOByInfoId',
// QUERY_DICT_NOTE_LIST : "PubService.getDictNoteDropList", // 获取数据字典
//
// };
//这边会有上面两种情况;返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1
if (line.indexOf("\'")==-1 && line.indexOf("\"")!=-1 ) {//不是单引号.是双引号
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf("\"")+1,line.indexOf("Service.")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}else if(line.indexOf("\'")!=-1 && line.indexOf("\"")==-1 ){//不是双引号.是单引号 QUERY_BANK_ACC_LIST : "TransferApplyTawbPageService
serviceMane = "";
serviceFinalName = "";
serviceMane = (line.substring(line.indexOf("\'")+1,line.indexOf("Service.")+7)).trim();
if (serviceMane.contains("Page")) {
serviceFinalName = serviceMane.split("Page")[0]+"EnPage"+serviceMane.split("Page")[1];
}else {
serviceFinalName = serviceMane.split("Service")[0]+"EnService";
}
line = line.replace(serviceMane, serviceFinalName);
}else {
continue;
}
}
}
}

}catch (IOException e) {
e.printStackTrace();
} // 读取下一行
}
buffer.append("\r\n"); // 添加换行符
String filecontent = buffer.toString().trim();

// 再输出到原文件
try {
File f = new File(filePathAndName);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream out = new FileOutputStream(filePathAndName);
byte[] bytes = null;
if (filePathAndName.endsWith(".java")) {
bytes = filecontent.getBytes("GBK");
}else {
bytes = filecontent.getBytes("utf-8");
}
out.write(bytes);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}else if (filePathAndName.endsWith(".java")) {
// tmSr.append(filePathAndName);
// tmSr.append("\r\n"); // 添加换行符
StringBuffer buffer = new StringBuffer();
String line = null; // 用来保存每行读取的内容
String readCellEnglishSecond = "";
String firstChineaeaString = "";
InputStream is = new FileInputStream(filePathAndName);
BufferedReader reader = null;
if (filePathAndName.endsWith(".java")) {
reader = new BufferedReader(new InputStreamReader(is,"GBK"));
}else {
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
}
try {
line = reader.readLine();
//将每一行的汉字替换成英文
if (line!=null) {
//如果是注释或者@logMethod这样的就不翻译
Boolean isTrueBoolean = isValite(line);
if (isTrueBoolean == false) {
StringBuilder tmSr = new StringBuilder();
tmSr.append(deepMatcher(line));
if (!"".equals(tmSr.toString())) {
String[] stringsTStrings = tmSr.toString().split("\r\n");
for (int i = 0; i < stringsTStrings.length; i++) {
if (cellChinaeseFirst.equals(stringsTStrings[i].trim())) {
readCellEnglishSecond = "\"+getEnOrCnMsg("+"\""+cellChinaeseFirst+"\""+","+"\""+cellEnglishSecond+"\""+")+\"";
if (line.indexOf("\"")!=-1) {
//throw new PBBusiException(PBBusiException.ERROR_BUSI_DEFAULT,"当前资金状态【已提交验资】,不能修改!");
//throw new PBBusiException(PBBusiException.ERROR_BUSI_DEFAULT,"当前资金状态【已提交验资】,"+getEnOrCnMsg("不能修改","Cannot modify")+"!");
//firstChineaeaString = line.substring(line.indexOf(cellChinaeseFirst.trim()), line.lastIndexOf("\"")+1);
line = line.replace(cellChinaeseFirst, readCellEnglishSecond);
}else if (line.indexOf("\'")!=-1) {
//firstChineaeaString = line.substring(line.indexOf(cellChinaeseFirst.trim())-1, line.lastIndexOf("\'")+1);
line = line.replace(cellChinaeseFirst, readCellEnglishSecond);
}
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("\r\n"); // 添加换行符
try {
line = reader.readLine();
//将每一行的汉字替换成英文
if (line!=null) {
//如果是注释或者@logMethod这样的就不翻译
Boolean isTrueBoolean = isValite(line);
if (isTrueBoolean == false) {
StringBuilder tmSr = new StringBuilder();
tmSr.append(deepMatcher(line));
if (!"".equals(tmSr.toString())) {
String[] stringsTStrings = tmSr.toString().split("\r\n");
for (int i = 0; i < stringsTStrings.length; i++) {
if (cellChinaeseFirst.equals(stringsTStrings[i].trim())) {
readCellEnglishSecond = "\"+getEnOrCnMsg("+"\""+cellChinaeseFirst+"\""+","+"\""+cellEnglishSecond+"\""+")+\"";
if (line.indexOf("\"")!=-1) {
//throw new PBBusiException(PBBusiException.ERROR_BUSI_DEFAULT,"当前资金状态【已提交验资】,不能修改!");
//throw new PBBusiException(PBBusiException.ERROR_BUSI_DEFAULT,"当前资金状态【已提交验资】,"+getEnOrCnMsg("不能修改","Cannot modify")+"!");
//firstChineaeaString = line.substring(line.indexOf(cellChinaeseFirst.trim()), line.lastIndexOf("\"")+1);
line = line.replace(cellChinaeseFirst, readCellEnglishSecond);
}else if (line.indexOf("\'")!=-1) {
//firstChineaeaString = line.substring(line.indexOf(cellChinaeseFirst.trim())-1, line.lastIndexOf("\'")+1);
line = line.replace(cellChinaeseFirst, readCellEnglishSecond);
}
}
}
}
}
}
}catch (IOException e) {
e.printStackTrace();
} // 读取下一行
}
buffer.append("\r\n"); // 添加换行符
String filecontent = buffer.toString().trim();

// 再输出到原文件
try {
File f = new File(filePathAndName);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream out = new FileOutputStream(filePathAndName);
byte[] bytes = null;
if (filePathAndName.endsWith(".java")) {
bytes = filecontent.getBytes("GBK");
}else {
bytes = filecontent.getBytes("utf-8");
}
out.write(bytes);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


/**
* 去重
* @param list
* @return
*/
public static List<String> removeDuplicate(List<String> list){
List<String> listTemp = new ArrayList<String>();
for(int i=0;i<list.size();i++){
//确认的黑名单
if (list.get(i).endsWith("frameHead.jsp")) {
continue;
}
if(!listTemp.contains(list.get(i))){
listTemp.add(list.get(i));
}
}
return listTemp;
}

public static String deepMatcher(String filecontent) throws Exception {
StringBuilder tmSr = new StringBuilder();
String regex = "[\u4e00-\u9fa5]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(filecontent);

//如果文件没有汉字,则文件路径不要出来
// if (matcher.find()!=false) {
// tmSr.append(filePathAndName);
// tmSr.append("\r\n"); // 添加换行符
// }

int tmp = -1;
boolean isBroke = false;//是否连续
boolean isPoint = false;//是否是. 的。
while (matcher.find()) {
MatchResult result = matcher.toMatchResult();
int start = result.start();
int end = result.end();
if(tmp == start || tmp == -1) {
// 判断连续
if (start>0) {
if(".".equals(filecontent.substring(start-1, end-1))!=true){
if (isPoint == false && isBroke==false) {
tmSr.append(filecontent.substring(start, end));
}
}else {
isPoint = true;
}
}else {
tmSr.append(filecontent.substring(start, end));
}
}else {
isBroke=true;
isPoint = false;
// 不连续
//空格,逗号,nbsp;斜杠/,+号,
if(filecontent.substring(tmp, start).matches("^\\s*")
|| filecontent.substring(tmp, start).matches(",(.*)")
|| filecontent.substring(tmp, start).matches(",(.*)")
|| filecontent.substring(tmp, start).matches("&nbsp;(.*)")
|| filecontent.substring(tmp, start).matches("/(.*)")
|| filecontent.substring(tmp, start).matches("\\+(.*)")
|| filecontent.substring(tmp, start).matches("[0-9]*")
|| filecontent.substring(tmp, start).matches("、")//将基金资产以及托管户、募集户产生的利息(如有)按投资者持有份额比例分配并原路径返还至投资者收益账户
|| filecontent.substring(tmp, start).matches("(")
|| filecontent.substring(tmp, start).matches(")")
) {
//特殊情况
if (filecontent.substring(tmp, start).matches("&nbsp;(.*)")) {
tmSr.append("");
}else if (filecontent.substring(tmp, start).matches(",(.*)") && filecontent.substring(tmp, start).matches(", \"(.*)")) {
//String str = "提交, \"重新提交\" ";属于逗号里面的特殊情况
tmSr.append("\r\n");
}else if (filecontent.substring(tmp, start).matches(",(.*)") && filecontent.substring(tmp, start).matches(",'(.*)")) {
//String str = "提交, \"重新提交\" ";属于逗号里面的特殊情况
tmSr.append("\r\n");
}else if (filecontent.substring(tmp, start).matches(",(.*)") && filecontent.substring(tmp, start).matches(".*[0-9|a-z|A-Z]+.*")) {
//String str = "个性化报表审批, this.getUserID(), this.getUserName(), this.getManagerID(), ActionGroup.暂存 ";
tmSr.append("\r\n");
}else if (filecontent.substring(tmp, start).matches(",(.*)") && filecontent.substring(tmp, start).matches(", \"(.*)")) {
//String str = "提交, \"重新提交\" ";属于逗号里面的特殊情况
tmSr.append("\r\n");
}else if (filecontent.substring(tmp, start).matches(",(.*)") && filecontent.substring(tmp, start).matches(",'(.*)")) {
//String str = "提交, \"重新提交\" ";属于逗号里面的特殊情况
tmSr.append("\r\n");
}else if (filecontent.substring(tmp, start).matches(",(.*)") && filecontent.substring(tmp, start).matches(".*[0-9|a-z|A-Z]+.*")) {
//String str = "个性化报表审批, this.getUserID(), this.getUserName(), this.getManagerID(), ActionGroup.暂存 ";
tmSr.append("\r\n");
}else {
tmSr.append(filecontent.substring(tmp, start));
}
}else {
tmSr.append("\r\n");
}

if (start>0) {
if(".".equals(filecontent.substring(start-1, end-1))!=true){
if (isPoint == false && isBroke==true) {
isBroke=false;
tmSr.append(filecontent.substring(start, end));
}
}else {
isPoint = true;
}
}else {
tmSr.append(filecontent.substring(start, end));
}
}
tmp = end;
}
if (tmSr.toString().contains("(")==true && tmSr.toString().contains(")")!=true) {
tmSr.append(")");
}
tmSr.append("\r\n"); // 添加换行符
return tmSr.toString();
}

/**
* 如果是注释或者@logMethod这样的则返回true
* @param line
* @return
*/
public static boolean isValite(String line){
line = line.trim();
if ( line != null && line.contains("@LogMethod")) {
return true;
}else if ( line != null && line.contains("@LogClass")) {
return true;
}else if ( line != null && line.contains("logger.info(")) {
return true;
}else if ( line != null && line.contains("logger.error(")) {
return true;
}else {
// 1、清除单行的注释,如: //某某,正则为 :\ / \ /.*
// 2、清除单行的注释,如:/** 某某 */,正则为:\/\*\*.*\*\/
// 3、清除单行的注释,如:/* 某某 */,正则为:\/\*.*\*\/
// 4、清除多行的注释,如:
// /* 某某1
// 某某2
// */
// 正则为:.*/\*(.*)\*/.*
// 5、清除多行的注释,如:
// /** 某某1
// 某某2
// */
// 正则为:/\*\*(\s*\*\s*.*\s*?)*
Map<String, String> patterns = new HashMap<String, String>();
patterns.put("([^:])\\/\\/.*", "$1");// 匹配在非冒号后面的注释,此时就不到再遇到http://
patterns.put("\\s+\\/\\/.*", "");// 匹配“//”前是空白符的注释
patterns.put("^\\/\\/.*", "");
patterns.put("^\\/\\*\\*.*\\*\\/$", "");
patterns.put("\\/\\*.*\\*\\/", "");
patterns.put("/\\*(\\s*\\*\\s*.*\\s*?)*\\*\\/", "");
//patterns.put("@LogMethod(?)", "");

//patterns.put("/\\*(\\s*\\*?\\s*.*\\s*?)*", "");
Iterator<String> keys = patterns.keySet().iterator();
String key = null, value = "";
while (keys.hasNext()) {
// 经过多次替换
key = keys.next();
value = patterns.get(key);
line = replaceAll(line, key, value);
}
if ("".equals(line)) {//这个就说明是注释
return true;
}
}
return false;
}

public static String replaceAll(String fileContent, String patternString,
String replace) {
String str = "";
Matcher m = null;
Pattern p = null;
try {
p = Pattern.compile(patternString);
m = p.matcher(fileContent);
str = m.replaceAll(replace);
} catch (Exception e) {
e.printStackTrace();
} finally {
m = null;
p = null;
}
// 获得匹配器对象
return str;
}

@SuppressWarnings("resource")
public static String fileUrlList(String rootDir ) throws Exception {
StringBuffer buffer = new StringBuffer();
String line = null; // 用来保存每行读取的内容
//去重后的纯路径的文件
InputStream is = new FileInputStream(rootDir);
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is,"GBK"));

try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("\r\n"); // 添加换行符
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
} // 读取下一行
}
buffer.append("\r\n"); // 添加换行符
return buffer.toString();
}
}

posted @ 2021-05-08 13:34  rearboal  阅读(256)  评论(0编辑  收藏  举报