⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testreg.java

📁 替换jsp中的中文为sturts中的bundle
💻 JAVA
字号:
package com.pengjj.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: </p>
 * @author pengjj
 * @version 1.0
 */
public class TestReg {
	//被替换的字符串
	static String replaceStr="";
	static String fileName = "";

	public static void main(String[] args) {
		/**
		 *  将jsp文件中的<%=map.get("RC_CKD_CKDBH")%>替换为<bean:write name="map" property="RC_CKD_CKDBH"/>
		 */
		/*来源文件路径,可以是文件夹,新生成的文件将替换原先的文件*/
		String sourceName = "d:/test";
		
		/*需要进行那种方式替换*/
		//String flag="beanwrite";//beanwrite替换
		String flag="beanmessage";//beanmessage替换
		
		/*资源文件名称*/
		String resourceName="d:/test/resources_zh_CN.txt";//
		
		//资源文件替换过程日志
		String replaceResultLog="d:/replacelog.txt";
		
		if(flag.equals("beanwrite")){ //bean:write转化
			File file = new File(sourceName);
			formatBeanWrtite(file);
		}else if(flag.equals("beanmessage")){//bean:message转化
			/**
			 * 替换jsp文件中的汉字为对应资源中的key
			 */
			File file = new File(sourceName);
			formatBeanMessage(file,resourceName);
			//生成日志文件
			replaceLog(replaceResultLog,replaceStr);
		}
		
		
		//转化为大写字母
//		String upperCaseFileName="D:/was/profiles/default/installedApps/pengjjNode01Cell/zhongcl.ear/zhongcl.war/zclroot/stock";
//		File upperCaseFile = new File(upperCaseFileName);
//		formatUpperCase(upperCaseFile);
		
	}
	/**
	 * 将jsp文件中的<%=map.get("RC_CKD_CKDBH")%>替换为<bean:write name="map" property="RC_CKD_CKDBH"/>
	 * @param str jsp文件的内容
	 * @return 返回替换后的结果
	 */
	public static void convertBeanWrite(String fileName,String replacedFile){
		String strFile=getFileContent(fileName);//文件内容
		String result="";//替换后的结果		
		int begin=0;//开始位置		
		int end=0;//结束位置
		String match="";//匹配的字符串
		//规则
		String regEx="<%=map.get\\(\""+"([a-zA-Z_0-9])+"+"\"\\)%>";
		String replace="";//替换结果的模板
        Pattern p=Pattern.compile(regEx);
        Matcher m=p.matcher(strFile);
        int i=0;
        int count=1;
        while(m.find()){
        	count++;        	
        }
        //在</head>加入标签  <logic:iterate id="map" type="java.util.Map">  以及body前加上</logic:iterate>
        /*if(count>1){
        	String regTemp="</head>";
        	String replaceTemp = "</head>\r\n    <logic:iterate id=\"map\" type=\"java.util.Map\">";
        	strFile = strFile.replaceAll(regTemp,replaceTemp);
        	regTemp="</body>";
        	replaceTemp = "</body>\r\n</logic:iterate>";
        	strFile = strFile.replaceAll(regTemp,replaceTemp);
        }*/
        System.out.println("---------jsp页面"+fileName+"中将要被替换的map.get代码有--"+(count-1)+"处-------------------");
        for(i=0;i<=count;i++){
           if(m.find()){
           match = m.group();
           begin=match.indexOf("\"");
           end=match.lastIndexOf("\"");   
           //<bean:write name="map" property="RC_RKD_ZGKRKTZDNM"/>
           replace="<bean:write name=\"map\" property=\""+match.subSequence(begin+1,end)+"\"/>";
          // i++;
           strFile=m.replaceFirst(replace);
           //System.out.println(i);
           //System.out.println(str);
           m=p.matcher(strFile);}
       }
        result=strFile;
        //将替换完成后的字符串写入文件
        if (count >1 ) {
    		replaceLog(replacedFile, result);
			System.out.println("---------jsp页面"+fileName+"中的map.get代码转为bean:write样式成功!");
		} else {
			System.out.println("---------jsp页面"+fileName+"中没有需要转为的代码!");
		}
	}
	
	/**
	 * 替换jsp文件中的汉字为对应资源中的key
	 * 
	 * @param resourceName
	 *            资源文件名称
	 * @param jspName
	 *            jsp来源文件名称
	 * @param newFile
	 *            新生成的jsp文件名称
	 */
	public static void convertResource(String resourceName,String jspName,String newFile){
		HashMap map= new HashMap();
		map = getMap(resourceName);		
		//将jsp中的中文字符读入到缓存中,对其中的中文进行替换
		String result=getFileContent(jspName);		
		//将资源文件读入str中,然后进行分割
		String temp[]=replaceByEqual(getFileContent(resourceName)).split("=");
		//替换后的字符串
		String replace="";
		String reg=""; //模板
		for(int i=0;i<temp.length;i++){
			if(temp[i]!=null||temp[i].trim()!=""){
				reg=">\r*\n*\\s*"+temp[i]+"\\s*\r*\n*<";
				result=convertBean(result,reg,(String)map.get(">"+temp[i]+"<"));
			}
		}
		//将改变的文件保存到原文件中
		FileOutputStream fos;
		try {
			fos = new FileOutputStream( new File(newFile));
			fos.write(result.getBytes());
			fos.flush();
			fos.close();
			System.out.println(jspName+"替换文件成功,新文件名为:"+newFile);
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	/**
	 * 生成资源文件替换日志文件
	 * @param logFile 日志文件名称
	 */
	public static void replaceLog(String logFile,String log){
		//将改变的文件保存到原文件中
		FileOutputStream fos;
		try {
			fos = new FileOutputStream( new File(logFile));
			fos.write(log.getBytes());
			fos.flush();
			fos.close();
		} catch (Exception e) {
			System.out.println("日志文件生成出错");
			e.printStackTrace();
		}	
	}
	/**
	 * 将文件读入string中
	 * @param fileName 文件名称
	 * @return String str
	 */
	public static String getFileContent(String fileName){
		String fileStr="";
		File file= new File(fileName);
		try {
			FileInputStream fis = new FileInputStream(file);
			byte[] b = new byte[(int)file.length()];
			int count = fis.read(b);
			fileStr += new String(b);
			fis.close();			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileStr;
	}
	/**
	 * 将文件中的回车或者换行符号替换为"="
	 * @param fileName
	 * @return
	 */
	public static String replaceByEqual(String str){
		return str.replaceAll("\r\n","=");		
	}
	/**
	 * 将资源的value存入map中的key中,将key放入value中
	 * @param fileName 文件名称
	 * @return HashMap hashMap
	 */
	public static HashMap getMap(String fileName){
		HashMap hashMap=new HashMap();
		File file= new File(fileName);
		String readLine = "";
		try {
			FileInputStream fis = new FileInputStream(file);
			byte[] b = new byte[(int)file.length()];
			String resourceStr = "";
			int count = fis.read(b);
			resourceStr += new String(b);
			resourceStr =replaceByEqual(resourceStr);
			//System.out.println(resourceStr);
			String []str1=resourceStr.trim().split("=");
			int i=0;
			int j = 1;
			while (i < str1.length - 1) {
				hashMap.put(">"+str1[j].trim()+"<", str1[i].trim());
				i = i + 2;
				j = j + 2;
			}
			fis.close();			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hashMap;
	}

	/**
	 * 将str替换为key
	 * @param fileStr 文件字符串 
	 * @param str 需要被替换的字符 reg
	 * @param key 资源文件中的key
	 * @return
	 */
	public static String convertBean(String fileStr,String str,String key){
		String reg=str;
		String replace="";
		replace = "><bean:message key=\""+key+"\" bundle=\"tongyong\"/><";
		try{
			Pattern pattern = Pattern.compile(reg);
			Matcher match = pattern.matcher(fileStr);//<bean:message key="common.chaxun" bundle="tongyong"/>
			if (match.find()) {
				replaceStr += "\""+str +"\""+ " ------被替换为----- \"" + replace +"\"\r\n";
			}else{
				replaceStr +="没有可以替换的中文";
			}
				
			fileStr = match.replaceAll(replace);
		}catch(Exception e){
			System.out.println("beanmessage替换失败"+e.getMessage());
		}
		return fileStr;
	}
	/**
	 * BeanWrite 格式转化
	 * @param file 来源文件路径
	 */
	public static void formatBeanWrtite(File file)  {
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					formatBeanWrtite(files[i]);
				}
			} else if(file.isFile() && validate(file)) {
				try {
					fileName = file.getPath();
					//对jsp文件进行转化
					convertBeanWrite(fileName,fileName);
				} catch (Exception e) {
					System.out.println("File have some error:" + file.getPath());
				}
			}
		}
	}
	/**
	 *BeanMessage 格式转化
	 * @param file 文件路径
	 * @param resourceName 资源文件名称
	 */
	public static void formatBeanMessage(File file,String resourceName) {		
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					formatBeanMessage(files[i],resourceName);
				}
			} else if(file.isFile() && validate(file)) {
				try {
					fileName = file.getPath();
					convertResource(resourceName,fileName,fileName);
				} catch (Exception e) {
					System.out.println("formatBeanMessage File have some error:" + file.getPath());
				}
			}
		}
	}
	/**
	 * jsp文件类型
	 * @param file 文件
	 * @return boolean 是否是jsp类型
	 */
	public static boolean validate(File file) {
        if (file.getName().endsWith(".jsp")) {
            return true;
        }
        return false;
    }
	/**
	 * 循环得到文件夹下的所有文件,然后进行大写字母的转化
	 * @param file 文件夹
	 */
	public static void formatUpperCase(File file){
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					formatUpperCase(files[i]);
				}
			} else if(file.isFile() && validate(file)) {
				try {
					fileName = file.getPath();
					convertToUpperCase(fileName);//进行转化
				} catch (Exception e) {
					System.out.println("formatBeanMessage File have some error:" + file.getPath());
				}
			}
		}
	}
	/**
	 *转为大写字母
	 * @param fileName 文件路径
	 */
	public static void convertToUpperCase(String fileName){
		String strFile=getFileContent(fileName);//文件内容
		String result="";//替换后的结果		
		int begin=0;//开始位置		
		int end=0;//结束位置
		String match="";//匹配的字符串
		//<bean:message key="common.baocun" bundle="TONGYONG"/>
		//规则
		//String regEx="<bean:message key=\""+"([A-z_0-9.])+"+"\"";
		//String regEx="<bean:message key=\"COMMON.";
		//String regEx="<bean:message key=\"TONGYONG.XINXILIEBIAO\" bundle=\"TONGYONG\"/>";
		String regEx="//flag=";
		String replace="";//替换结果的模板
        Pattern p=Pattern.compile(regEx);
        Matcher m=p.matcher(strFile);
        int i=0;
        int count=1;
        while(m.find()){
        	count++;        	
        }//System.out.println(count);
        for(i=0;i<=count;i++){
           if(m.find()){
           match = m.group();
           begin=match.indexOf("\"");
           end=match.lastIndexOf("\"");   
           //转化为大写字母
           //replace="<bean:message key=\""+match.subSequence(begin+1,end).toString().toUpperCase()+"\"";
           //replace="<bean:message key=\"TONGYONG.";
           replace="flag=";
          // i++;
           strFile=m.replaceFirst(replace);
           System.out.println(i);
           System.out.println(replace);
           m=p.matcher(strFile);
           }
       }
        result=strFile;
        //将替换完成后的字符串写入文件
        if (count >1 ) {
    		replaceLog(fileName, result);
			System.out.println("---------jsp页面"+fileName+"中的BeanMessage 中的key转为大写字母成功!");
		} else {
			System.out.println("---------jsp页面"+fileName+"中没有需要转为的代码!");
		}
		
	}
	/**
	 * 循环得到文件夹下的所有文件,然后进行大写字母的转化
	 * @param file 文件夹
	 */
	public static void replaceStr(File file,String reg,String replace){
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					replaceStr(files[i],reg,replace);
				}
			} else if(file.isFile() && validate(file)) {
				try {
					fileName = file.getPath();
					replace(fileName,reg,replace);//进行转化
				} catch (Exception e) {
					System.out.println("formatBeanMessage File have some error:" + file.getPath());
				}
			}
		}
	}
	/**
	 * 替换文件目录下所有文件的部分字符串
	 * @param fileName 文件名称
	 * @param reg 正则表达式
	 * @param replace 替换字符串
	 */	
	public static void replace(String fileName, String reg, String replace) {
        /* 读取文件的全部字符串内容 */
        String strFile = getFileContent(fileName); //文件内容
        String result = ""; //替换后的结果
        int begin = 0; //开始位置
        int end = 0; //结束位置
        String match = ""; //匹配的字符串

        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(strFile);
        result = m.replaceFirst(replace);
        //将替换完成后的字符串写入文件
        replaceLog(fileName, result);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -