项目打包class文件(打补丁更新)的工具类

1.创建update.txt,为相对路径加/方式

/tobacco_qdn/WebRoot/WEB-INF/pages/regulation/training/files/list.jsp
/tobacco_qdn/regulation/cn/mos/restructure/controller/training/files/TrainingFiles.java

2.创建getFile工具类,适当修改配置

package cn.mos;


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.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * @author
 * @name IgagaCinemasAction
 */

public class GetFile {
    private static long lastmodifytime = 3 * 24 * 60 * 60 * 1000;  //默认找两小时内的文件,用于getTxtByTime方法来更新update.txt
    private static String resultFloder = "C:\\Users\\jrkj_21\\Desktop\\upload";  //导出文件放的位置
    private static String projectname = "";//工程名称

    public static void main(String[] args) throws IOException {
//			getTxtByTime();//打印出近期更新文件,时间以lastmodifytime为准

        proFileByTxt(); //根据update.txt输出更新文件

    }


    private static String baseFloderNoproject = null;
    private static String baseFloder = null;
    private static String updatefile = null;
    private static String webRoot = "WebRoot";  //工程WebRoot地址,一般不改	

    static {
        //*********************默认配置为当前工程,不用管********************************/
        baseFloder = GetFile.class.getResource("/").toString();
        if (baseFloder != null) {
            baseFloder = baseFloder.substring(6, baseFloder.indexOf("/WebRoot"));//如果是windwos将5变成6  
            baseFloder = baseFloder.replaceAll("\\/", "\\\\");
            projectname = baseFloder.substring(baseFloder.lastIndexOf("\\") + 1);
            baseFloderNoproject = baseFloder.substring(0, baseFloder.lastIndexOf("\\"));
            resultFloder = resultFloder + "\\" + projectname;
        }
        System.out.println("当前工程路径" + baseFloder);
        updatefile = baseFloder + "\\src\\update.txt";   //升级文档
        System.out.println("升级文档路径" + updatefile);
        //*********************默认配置为当前工程,不用管********************************/


    }


    private static void getTxtByTime() {
        File dir = new File(baseFloder);
        System.out.println("");
        System.out.println("");
        System.out.println("============以下为近期更新文件=================");
        getTxtByTime(dir);//根据时间,更新update.txt			
    }

    private static void getTxtByTime(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                getTxtByTime(new File(dir, children[i]));
            }
        } else {
            //如果不是目录 
//		        	Calendar cl = java.util.Calendar.getInstance();
//	        		cl.setTimeInMillis(dir.lastModified());
//	        		System.out.println(dir.lastModified()+" "+Kit.formatDate(cl.getTime(), "yyyy-MM-dd"));
            if ((System.currentTimeMillis() - dir.lastModified()) < lastmodifytime) {
                if (dir.getName().contains(".") && !dir.getName().endsWith(".class") && !dir.getName().endsWith(".txt") && !dir.getName().contains(".svn")) {
                    if (!dir.getPath().contains("\\WEB-INF\\classes\\")) {
                        if (!dir.getName().contains("GetFile")) {//排除掉当前文件
                            long timemiao = (System.currentTimeMillis() - dir.lastModified()) / 1000;
                            String selfpath = dir.getAbsolutePath();
                            if (selfpath.contains("src")) {
                                selfpath = selfpath.substring(selfpath.indexOf("src") + 4);
                                selfpath = selfpath.replaceAll("\\\\", ".");
                            }
                            if (selfpath.contains(webRoot)) {
                                selfpath = selfpath.substring(selfpath.indexOf(webRoot));
                            }
//		        					selfpath = selfpath.substring();
//		        					System.out.println(selfpath);
                            //System.out.println(dir.getName()+" "+dir.lastModified());
                        }
                    }
                }
            }
        }
    }

    private static void proFileByTxt() {
        List loglist = new ArrayList();

        if (!resultFloder.contains("upload")) {
            System.out.println("安全警告,建议输出目录名包括upload,防止错误的删除一般目录");
            return;
        }
        File rfloder = new File(resultFloder);
        if (!rfloder.exists()) {
            rfloder.mkdirs();
        } else {
            System.out.println("===================输出目录存在,删除重建================");
            deleteDir(rfloder);
            rfloder.mkdirs();
        }
        Map map = readUpdateFile(updatefile, baseFloder, webRoot, resultFloder, loglist);//读升级文档
        copyFiles(map, loglist);//把文件拷贝到另一外文件夹
        writelog(resultFloder, loglist);//写日志
    }


    private static void writelog(String resultFloder, List loglist) {
        File rfloder = new File(resultFloder);
        if (!rfloder.exists()) {
            rfloder.mkdirs();
        }
        rfloder = new File(resultFloder);
        String logcontent = "";
        for (int i = 0; i < loglist.size(); i++) {
            logcontent += (String) loglist.get(i) + "\r\n";
        }
        writeFile(rfloder.getAbsolutePath() + "\\更新log.txt", logcontent, "gbk");
    }

    /**
     * 递归获取文件列表
     *
     * @param tempbp
     * @param rsbp
     * @param map
     */
    private static void getFilsByFloler(String tempbp, String rsbp, Map map) {
        File tf = new File(tempbp);
        if (tf.exists() && tf.isDirectory()) {
            File[] fs = tf.listFiles();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].isFile()) {
                        map.put(tempbp + fs[i].getName(), rsbp + fs[i].getName());
                    } else if (fs[i].isDirectory()) {
                        String next_tempbp = tempbp + fs[i].getName() + "\\";
                        String next_rsbp = rsbp + fs[i].getName() + "\\";
                        getFilsByFloler(next_tempbp, next_rsbp, map);
                    }
                }
            }
        } else if (tf.isFile()) {
            map.put(tempbp + tf.getName(), rsbp + tf.getName());
        }
    }

    private static Map readUpdateFile(String updatefile, String baseFloder, String webRoot, String resultFloder, List loglist) {
        LinkedHashMap map = new LinkedHashMap();
        try {
            File file = new File(updatefile);
            if (file.exists()) {  //文件存在时  

                if (!resultFloder.endsWith("\\")) {//统一添加结尾的斜杠
                    resultFloder = resultFloder.replaceAll("/", "\\");
                    resultFloder += "\\";
                }
                if (!baseFloder.endsWith("\\")) {//统一添加结尾的斜杠
                    baseFloder = baseFloder.replaceAll("/", "\\");
                    baseFloder += "\\";
                }


                String line;
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                int count = 0;
                while ((line = reader.readLine()) != null) {
                    if (line != null) {
                        line = line.trim();
                        String rs = "未处理";
                        String tempbp = "";
                        if (!"".equals(line)) {

                            if (line.contains("/WebRoot/")) {
                                line = "/" + line.split("/WebRoot/")[1];
//				    				  System.out.println(line);
                            }

                            if (line.startsWith("/" + projectname)) {//注意,新版本的myeclipse复制文件
                                int gedp = line.indexOf("/cn/");
                                if (gedp <= 3) {
                                    gedp = line.indexOf("/com/");
                                }
                                line = line.substring(gedp + 1);
                            }


                            if (line.endsWith(".java") && (line.startsWith("com") || line.startsWith("cn"))) {//类文件
                                if (line.endsWith(".java")) {
                                    line = line.substring(0, line.length() - 5);
                                }
                                tempbp = baseFloder + webRoot + "\\WEB-INF\\classes\\" + line.replaceAll("\\.", "\\\\") + ".class";
                                String rsbp = resultFloder + webRoot + "\\WEB-INF\\classes\\" + line.replaceAll("\\.", "\\\\") + ".class";
                                if (isExists(tempbp)) {
                                    rs = "路径正确 " + getTime(tempbp) + " ";
                                    map.put(tempbp, rsbp);
                                } else {
                                    rs = "不正确";
                                }

                                for (int i = 1; i < 10; i++) {
                                    String tempbp2 = baseFloder + webRoot + "\\WEB-INF\\classes\\" + line.replaceAll("\\.", "\\\\") + "$" + i + ".class";
                                    String rsbp2 = resultFloder + webRoot + "\\WEB-INF\\classes\\" + line.replaceAll("\\.", "\\\\") + "$" + i + ".class";

                                    if (isExists(tempbp2)) {
                                        map.put(tempbp2, rsbp2);
                                    } else {
                                        break;
                                    }

                                }


                            } else if (line.endsWith("xml") && (line.contains("cn") || line.contains("com"))) {
                                if (line.endsWith(".xml")) {
                                    line = line.substring(0, line.length() - 4);
                                }
                                tempbp = baseFloder + webRoot + "\\WEB-INF\\classes\\" + line.replaceAll("\\.", "\\\\") + ".xml";
                                String rsbp = resultFloder + webRoot + "\\WEB-INF\\classes\\" + line.replaceAll("\\.", "\\\\") + ".xml";
                                if (isExists(tempbp)) {
                                    rs = "路径正确 " + getTime(tempbp) + " ";
                                    map.put(tempbp, rsbp);
                                } else {
                                    rs = "不正确";
                                }

                            } else if (line.endsWith("xml")) {//配置文件


//				    				  tempbp = baseFloderNoproject+line;	
//				    				  line = line.replaceAll("/", "\\\\");
//				    				  if(line.startsWith("\\")){
//				    					  line =line.substring(1);
//				    				  }
//			    					  String rsbp = resultFloder+line;
//			    					  if(isExists(tempbp)){
//			        					  rs="路径正确 "+getTime(tempbp)+" ";
//			        					  map.put(tempbp, rsbp);
//			        				  }else{
//			        					  rs="不正确";
//			        				  }


//				    				  if(line.indexOf("\\")<0){
//				    					  tempbp = baseFloder+webRoot+"\\WEB-INF\\classes\\"+line;	 
//				    					  String rsbp = resultFloder+webRoot+"\\WEB-INF\\classes\\"+line;
//				    					  if(isExists(tempbp)){
//				        					  rs="路径正确 "+getTime(tempbp)+" ";
//				        					  map.put(tempbp, rsbp);
//				        				  }else{
//				        					  rs="不正确";
//				        				  }
//				    				  }else{
//				    					  line = line.replaceAll("/", "\\\\");
//					    				  if(line.startsWith("\\")){
//					    					  line =line.substring(1);
//					    				  }
//					    				  if(!line.startsWith(webRoot)){
//					    					  line = webRoot+"\\"+line;
//					    				  }
//					    				  tempbp = baseFloder+line;
//					    				  String rsbp = resultFloder+line;
//					    				  File tf = new File(tempbp);
//					    				  if(tf.exists()&&tf.isDirectory()&&!line.endsWith("\\")){
//					    					  tempbp = tempbp+"\\";
//					    					  rsbp = rsbp+"\\";
//					    				  }
//					    				  if(isExists(tempbp)){
//					    					  rs="路径正确 "+getTime(tempbp)+" ";
//					    					  map.put(tempbp, rsbp);
//					    				  }else{
//					    					  rs="不正确";
//					    				  }
//				    				  }
                            } else if (line.endsWith("*")) {
                                line = line.substring(0, line.length() - 1);
                                line = line.replaceAll("/", "\\\\");
                                if (line.startsWith("\\")) {
                                    line = line.substring(1);
                                }
                                if (!line.startsWith(webRoot)) {
                                    line = webRoot + "\\" + line;
                                }
                                if (!line.endsWith("\\")) {
                                    line = line + "\\";
                                }

                                tempbp = baseFloder + line;
                                String rsbp = resultFloder + line;
                                if (isExists(tempbp)) {
                                    rs = "路径正确******(注意,目录下全部被拷贝)" + getTime(tempbp) + " ";
                                    map.put(tempbp, rsbp);
                                } else {
                                    rs = "不正确";
                                }

                                //取该目录下的文件,注意,仅取其下一级文件,(目录不取)
                                File tf = new File(tempbp);
                                if (tf.exists() && tf.isDirectory()) {
                                    getFilsByFloler(tempbp, rsbp, map);
//				    					  File[] fs = tf.listFiles();
//				    					  if(fs!=null&&fs.length>0){
//				    						for (int i = 0; i < fs.length; i++) {
//				    							if(fs[i].isFile()){
//				    								map.put(tempbp+fs[i].getName(), rsbp+fs[i].getName());
//				    							}
//											}
//				    					  }
                                }


                            } else {//一般文件				    				 
                                line = line.replaceAll("/", "\\\\");
                                if (line.startsWith("\\")) {
                                    line = line.substring(1);
                                }
                                if (!line.startsWith(webRoot)) {
                                    line = webRoot + "\\" + line;
                                }
                                tempbp = baseFloder + line;
                                String rsbp = resultFloder + line;
                                File tf = new File(tempbp);
                                if (tf.exists() && tf.isDirectory() && !line.endsWith("\\")) {
                                    tempbp = tempbp + "\\";
                                    rsbp = rsbp + "\\";
                                }
                                if (isExists(tempbp)) {
                                    rs = "路径正确 " + getTime(tempbp) + " ";
                                    map.put(tempbp, rsbp);
                                } else {
                                    rs = "不正确";
                                }
                            }
                            String temlog = rs + " : " + ("".equals(tempbp) ? line : tempbp);
                            loglist.add(temlog);
                            System.out.println(temlog);
                        }
                    }
                }
                reader.close();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }

    private static void copyFiles(Map map, List loglist) {
        System.out.println("================================ ");
        System.out.println("开始拷贝 ");
        System.out.println("================================ ");
        loglist.add("================================ ");
        loglist.add("开始拷贝 ");
        loglist.add("================================ ");
        if (!map.isEmpty()) {
            Iterator it = map.keySet().iterator();
            while (it.hasNext()) {
                String logstr = "";
                String oldp = (String) it.next();
                String newp = (String) map.get(oldp);
                newp = newp.replaceAll("/", "\\\\");
                if (isExists(newp) && !new File(newp).isDirectory()) {//已经存在,且不是文件夹
                    logstr = "错误:已经存在文件 " + newp;
                    System.out.println(logstr);
                } else {
                    String path = newp;
                    path = newp.substring(0, path.lastIndexOf("\\"));
                    File newpath = new File(path);
                    if (!newpath.exists()) {
                        newpath.mkdirs();
                    }

                    copy(oldp, newp);
                    if (isExists(newp)) {
                        logstr = "正确:拷贝成功:" + newp;
                        System.out.println(logstr);
                    } else {
                        logstr = "错误:拷贝失败:" + newp;
                        System.out.println(logstr);
                    }
                }
                loglist.add(logstr);
            }
        }

    }

    private static boolean isExists(String filename) {
        File file = new File(filename);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    private static String getTime(String filename) {
        File file = new File(filename);
        Long time = file.lastModified();
        Calendar cd = Calendar.getInstance();
        cd.setTimeInMillis(time);
        return cd.getTime().toLocaleString();
    }


    private static boolean copy(String fileFrom, String fileTo) {
        try {
            FileInputStream in = new java.io.FileInputStream(fileFrom);
            FileOutputStream out = new FileOutputStream(fileTo);
            byte[] bt = new byte[1024];
            int count;
            while ((count = in.read(bt)) > 0) {
                out.write(bt, 0, count);
            }
            in.close();
            out.close();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    public static boolean writeFile(String filepath, String content, String code) {
        try {
            File file = new File(filepath);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStream outputStream = new FileOutputStream(file);
            Writer out = new OutputStreamWriter(outputStream, code);
            out.write(content);
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 删除空目录
     *
     * @param dir 将要删除的目录路径
     */
    private static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值