修改tomcat部署下,项目配置(涉及properties,xml,zip,war之间相互转换修改)

 思路:传入tomcat部署路径,
 1,遍历tomcat下所有的文件夹,因为要修改
 的文件都是固定,所以根据传入路径就能拼装要修改的文件。
 2,像1的解决思路,可能导致tomcat不断在启动,因为文件在修改。
 所以又想到,将要修改的war包改成Zip,因为其结构都一样,Zip不会
 自动部署,其他修改都一样。修改完后将zip后缀名改为war即可。
 注意解压目录需要更换一个其他目录,不要直接解压到部署目录下。
 
 遇到的问题:
  在修改文件时,一边读一边写,写的时候总是取不到文件,
  除非在断点的情况下,手动运行一下,后面才能取到,我想
  这可能是java在节约内存,不能同时用到两个流在一个文件操作。
  想到的解决方法是,先写到一个零时文件,然后再将这个零时文件
  复制到原文件,再将零时文件删除。
  在解压文件完成压缩后需要将解压后的文件删除,这时遇到到了一个
  文件不能删除的情况,通过网上的查找,找到一种gc回收机制,能解决。

 


下面给出关键代码:

 复制文件:
  private void copyFile(File fromFile,File toFile) throws IOException{
    FileInputStream ins = new FileInputStream(fromFile);
    FileOutputStream out = new FileOutputStream(toFile);
    byte[] b = new byte[1024];
    int n=0;
    while((n=ins.read(b))!=-1){
        out.write(b, 0, n);
    }
    
    ins.close();
    out.close();
    fromFile.delete();
	}
  
  
  修改properties文件
  @SuppressWarnings("unused")
	private void updateWeixin4jProperties(String path,String weChatappId,String weChatappSecret,
			String weChattoken,String weChatAESKey,String weixin4jaccount){
		String fileName=path+"/WEB-INF/classes/weixin4j.properties";
		String fileName1=path+"/WEB-INF/classes/weixin4jCopy.properties";
		 File file = new File(fileName);
		if(file.exists()){
			 BufferedReader reader = null;
       try {
          reader = new BufferedReader(new FileReader(file));
           File file1 = new File(fileName1);
           if(file1.exists()){
          	 file1.createNewFile();
           }
           FileWriter  out=new FileWriter (file1);
           BufferedWriter bw= new BufferedWriter(out);
           
           String tempString = null;
          // int line = 1;
           // 一次读入一行,直到读入null为文件结束
           while ((tempString = reader.readLine()) != null) {
          		 if(tempString.startsWith("weChat.appId=")){
          			 tempString="weChat.appId="+weChatappId;
          			 bw.write(tempString);
          			 bw.newLine();
          		 }else if (tempString.startsWith("weChat.appSecret=")) {
          			 tempString="weChat.appSecret="+weChatappSecret;
          			 bw.write(tempString);
          			 bw.newLine();
							}
          		 else if (tempString.startsWith("weChat.AESKey=")) {
          			 tempString="weChat.AESKey="+weChatAESKey;
          			 bw.write(tempString);
          			 bw.newLine();
							}
          		 else if (tempString.startsWith("weixin4j.account=")) {
          			 tempString="weixin4j.account="+weixin4jaccount;
          			 bw.write(tempString);
          			 bw.newLine();
							}
          		 
							else{
								 bw.write(tempString);
	         			 bw.newLine();
							}
           }
           reader.close();
           bw.flush();
           bw.close();
           out.close();
           copyFile(file1,file);
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           if (reader != null) {
               try {
                   reader.close();
               } catch (IOException e1) {
              	 e1.printStackTrace();
               }
           }
       }
			
			
		}
		
	}
  
  
  
  
  修改xml文件
  @SuppressWarnings({"rawtypes", "unused"})
	private void updateWebXml(String path,String casinneraddress, String casiloginaddress,  String applicationmatchaddress,  String applicationinneraddress,String statementserviceaddress){
		String fileName=path+"/WEB-INF/web.xml";
		
		 File file = new File(fileName);
		 
		 SAXReader reader1 = new SAXReader();
			if(file.exists()){
				 
	       try {
	      	 Document document = reader1.read(new FileReader(file));
	            // 通过document对象获取根节点rootStore
	            Element rootStore = document.getRootElement();
	            // 通过element对象的elementIterator方法获取迭代器
	            Iterator it = rootStore.elementIterator();
	            // 遍历迭代器,获取根节点中的信息
	         
	            int secondflag=0;
	            String thridflag="";
	            while (it.hasNext()) {
	               // System.out.println("=====开始遍历一节点=====");
	                Element first = (Element) it.next();
	                
	                // 获取book的属性名以及 属性值
	              //  System.out.println("一级节点名:" + first.getName() + "--一级节点值:" + first.getStringValue());
	                Iterator itt = first.elementIterator();
	                while (itt.hasNext()) {
	                    Element second = (Element) itt.next();
	               //     System.out.println("二级节点名:" +second.getName() + "--二级节点值:" + second.getStringValue());
	                    if(second.getStringValue().equals("CAS Single Sign Out Filter") && first.getName().equals("filter")){
	                    	secondflag=1;
	                    }else if(second.getStringValue().equals("CAS Validation Filter") && first.getName().equals("filter")){
	                    	secondflag=2;
	                    }else if(second.getStringValue().equals("CAS Authentication Filter") && first.getName().equals("filter")){
	                    	secondflag=3;
	                    }else if(second.getStringValue().equals("ProxyServlet") && first.getName().equals("servlet")){
	                    	secondflag=4;
	                    }
	                    
											Iterator ittt= second.elementIterator();
	                    while(ittt.hasNext()){
	                    	Element third= (Element)ittt.next();
	                  //  	  System.out.println("三级节点名:" + third.getName() + "--三级节点值:" + third.getStringValue());
	                    	  if(third.getName().equals("param-value") && secondflag==1
	                    	  		&& first.getName().equals("filter")){
	                    	  	if(!CheckUtil.isNullorEmpty(casinneraddress)){
	                    	  		third.setText(casinneraddress);
	                    	  	}
	                    	  	
	                    	  	secondflag=0;
	                    	  }else if(third.getName().equals("param-name") 
	                    	  		&& first.getName().equals("filter")){
	                    	  	thridflag=third.getStringValue();
	                    	  }else if(third.getName().equals("param-value") && secondflag==2 
	                    	  		&& first.getName().equals("filter") && thridflag.equals("casServerUrlPrefix")){
	                    	  	if(!CheckUtil.isNullorEmpty(casinneraddress)){
	                    	  		third.setText(casinneraddress);
	                    	  	}
	                    	  	thridflag="";
	                    	  }else if(third.getName().equals("param-value") && secondflag==2 
	                    	  		&& first.getName().equals("filter") && thridflag.equals("serverName")){
	                    	  	if(!CheckUtil.isNullorEmpty(applicationmatchaddress)){
	                    	  		third.setText(applicationmatchaddress);
	                    	  	}
	                    	  	thridflag="";
	                    	  }else if(third.getName().equals("param-value") && secondflag==2 
	                    	  		&& first.getName().equals("filter") && thridflag.equals("proxyCallbackUrl")){
	                    	  	
	                    	  	if(!CheckUtil.isNullorEmpty(applicationinneraddress)){
	                    	  		third.setText(applicationinneraddress+"mainWeb/proxyCallback");
	                    	  	}
	                    	  	thridflag="";
	                    	  }
	                    	  else if(third.getName().equals("param-value") && secondflag==3 
	                    	  		&& first.getName().equals("filter") && thridflag.equals("casServerLoginUrl")){
	                    	  	if(!CheckUtil.isNullorEmpty(casiloginaddress)){
	                    	  		third.setText(casiloginaddress);
	                    	  	}
	                    	  	thridflag="";
	                    	  }
	                    	  else if(third.getName().equals("param-value") && secondflag==3 
	                    	  		&& first.getName().equals("filter") && thridflag.equals("serverName")){
	                    	  	if(!CheckUtil.isNullorEmpty(applicationmatchaddress)){
	                    	  		third.setText(applicationmatchaddress);
	                    	  	}
	                    	  	thridflag="";
	                    	  }
	                    	  ///servlet
	                    	  else if(third.getName().equals("param-name") 
	                    	  		&& first.getName().equals("servlet")){
	                    	  	thridflag=third.getStringValue();
	                    	  }
	                    	  else if(third.getName().equals("param-value") && secondflag==4 
	                    	  		&& first.getName().equals("servlet") && thridflag.equals("url")){
	                    	  	if(!CheckUtil.isNullorEmpty(statementserviceaddress)){
	                    	  		third.setText(statementserviceaddress);
	                    	  	}
	                    	  	thridflag="";
	                    	  }
	                    	  
	                    }//  while(ittt.hasNext())
	                }//while (itt.hasNext()) 
	                thridflag="";
                  secondflag=0;
	            }
	           
	          OutputFormat format=OutputFormat.createPrettyPrint();
	          format.setEncoding("UTF-8");
	          XMLWriter writer=new XMLWriter(new FileOutputStream(fileName),format);
	          writer.write(document);
	          writer.close();
	          
	       }catch (Exception e) {
	      	 e.printStackTrace();
					}
			}
	}
  
  
  
  
  
  /**
   * 解压压缩包
   * 
   * @param zipFilePath 压缩文件路径带后缀名
   * @param destDir 解压目录
   */
  @SuppressWarnings("rawtypes")
	private void unZip(String zipFilePath, String destDir)
  {
  	//destDir=destDir+"/";
  	destDir=destDir+File.separator;
      ZipFile zipFile = null;
      try
      {
          BufferedInputStream bis = null;
          FileOutputStream fos = null;
          BufferedOutputStream bos = null;
          zipFile = new ZipFile(zipFilePath);
          Enumeration zipEntries = zipFile.entries();
          File file, parentFile;
          ZipEntry entry;
          byte[] cache = new byte[CACHE_SIZE];
          while (zipEntries.hasMoreElements())
          {
              entry = (ZipEntry) zipEntries.nextElement();
            
              if (entry.isDirectory())
              {
                  new File(destDir + entry.getName()).mkdirs();
                  continue;
              }
              bis = new BufferedInputStream(zipFile.getInputStream(entry));
              file = new File(destDir + entry.getName());
              parentFile = file.getParentFile();
              if (parentFile != null && (!parentFile.exists()))
              {
                  parentFile.mkdirs();
              }
              fos = new FileOutputStream(file);
              bos = new BufferedOutputStream(fos, CACHE_SIZE);
              int readIndex = 0;
              while ((readIndex = bis.read(cache, 0, CACHE_SIZE)) != -1)
              {
                  fos.write(cache, 0, readIndex);
              }
              bos.flush();
              bos.close();
              fos.close();
              bis.close();
          }
      }
      catch (IOException e)
      {
          e.printStackTrace();
      }
      finally
      {
          try
          {
              zipFile.close();
          }
          catch (IOException e)
          {
              e.printStackTrace();
          }
      }
  }
  
  
  压缩文件:
 /**
 * 
 * @param destFile 带后缀名
 * @param zipDir  文件夹名
 */
  private void zipWar(String destFile, String zipDir) {
    File outFile = new File(destFile);
    try {
        outFile.createNewFile();
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outFile));
        ArchiveOutputStream out = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR,
                bufferedOutputStream);

        if (zipDir.charAt(zipDir.length() - 1) != '/') {
            zipDir += '/';
        }

        Iterator<File> files = FileUtils.iterateFiles(new File(zipDir), null, true);
        while (files.hasNext()) {
            File file = files.next();
            ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getPath().replace(
                    zipDir.replace("/", "\\"), ""));
            out.putArchiveEntry(zipArchiveEntry);
            IOUtils.copy(new FileInputStream(file), out);
            out.closeArchiveEntry();
        }
        out.finish();
        out.close();
        bufferedOutputStream.close();
        System.gc();
    } catch (IOException e) {
        System.err.println("创建文件失败");
        e.printStackTrace();
    } catch (ArchiveException e) {
    	 e.printStackTrace();
        System.err.println("不支持的压缩格式");
    }
}
  
  
  
  
  /**
   * 删除目录及目录下的文件
   *
   * @param dir
   *            要删除的目录的文件路径
   * @return 目录删除成功返回true,否则返回false
   * @throws Exception 
   */
  public static boolean deleteDirectory(String dir) throws Exception {
      // 如果dir不以文件分隔符结尾,自动添加文件分隔符
      if (!dir.endsWith(File.separator))
          dir = dir + File.separator;
      File dirFile = new File(dir);      
      // 如果dir对应的文件不存在,或者不是一个目录,则退出
      if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
          System.out.println("删除目录失败:" + dir + "不存在!");
          return false;
      }
      boolean flag = true;
      // 删除文件夹中的所有文件包括子目录
      File[] files = dirFile.listFiles();
      for (int i = 0; i < files.length; i++) {
          // 删除子文件
          if (files[i].isFile()) {
              flag = deleteFile(files[i].getAbsolutePath());
              if (!flag)
                  break;
          }
          // 删除子目录
          else if (files[i].isDirectory()) {
              flag =deleteDirectory(files[i]
                      .getAbsolutePath());
              if (!flag)
                  break;
          }
      }
      if (!flag) {
          System.out.println("删除目录失败!");
          return false;
      }
      // 删除当前目录
      if (dirFile.delete()) {
        //  System.out.println("删除目录" + dir + "成功!");
          return true;
      } else {
          return false;
      }
  }

	
  
  
  
  
    /**
   * 删除单个文件
   *
   * @param fileName
   *            要删除的文件的文件名
   * @return 单个文件删除成功返回true,否则返回false
   * @throws Exception 
   */
  private static boolean deleteFile(String fileName) throws Exception {
      File file = new File(fileName);
      // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
      if (file.exists() && file.isFile()) {
      	boolean falg=false;
      	int tryCount = 0;  
  	    while(!falg && tryCount++ <10)  
  	    {  	    
  	    	System.gc();  
  	    	falg = file.delete();  
  	    } 
      	
      
          if (falg) {
            //  System.out.println("删除单个文件" + fileName + "成功!");
              return true;
          } else {
              System.out.println("删除单个文件" + fileName + "失败!");
              return false;
          }
      } else {
          System.out.println("删除单个文件失败:" + fileName + "不存在!");
          return false;
      }
  }
  
  
  

	压缩包改名
	private void changeName(String path){
		 File file = new File(path);  
		 file.renameTo(new File(path.substring(0,path.lastIndexOf("."))+".war" ));
	}
	




import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值