更新提取小工具

package tool;

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.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

扫描二维码关注公众号,回复: 220496 查看本文章

import java.util.List;

import org.apache.log4j.Logger;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.input.SAXBuilder;

import org.jdom.xpath.XPath;

/**

 * 代码提取更新工具

 * @author Administrator

 *

 */

public class MyToolApp

{

 private static Logger logger = Logger.getLogger(MyToolApp.class);   

 // private Display display;

 // private Shell shell;

  private String text_directory; // 文件目录

  private String text_outputdirectory;// 输出目录 

  private String text_starttime;

  private String text_endtime;

  

  private boolean containsSrc = false;//是否包含源码

  

  private String directory;

  private String projectName;//项目名称

  private String outputdirectory;//输出目录

  private long long_starttime;//开始时间

  private long long_endtime;//结束时间

  private boolean bool_starttime = false;//

  private boolean bool_endtime = false;

  private boolean bool = true;// 是否文件修改标志 

  

  private boolean isWebProject = false ;//是否web工程

  private List<String> src = null;

  private String output = "WebRoot/WEB-INF/classes";// 文本输出的目录 

  private String web_root_folder = "WebRoot";

  private String configName;//src 要复制的源文件格式 

  

 // private String output = "bin";

  //private String web_root_folder = "bin";

  private int sumcount;

  private int successcount;

  private long start;

  /**

   * 更新文件 

   */

  public void open()

  { 

  }

  /**

   *  更新文件操作 

   */

  public void search() {

    this.start = System.currentTimeMillis();

    /// 验证数据  

    validate();

    this.sumcount = 0;

    this.successcount = 0;

    this.src = new ArrayList();

    if (this.bool)

    {

      try {

    // 读取class 

        readClassPath();

        String str = "";

        File f = null;

        File file = null;

        ArrayList list = null;

        String abspath = "";

        for (int i = 0; i < this.src.size(); i++) {

          str = this.directory + "/" + (String)this.src.get(i);

          f = new File(str);

          if ((f.exists()) && (f.isDirectory())) {

            list = getSubFiles(f);

            if (!list.isEmpty()) {

              for (int j = 0; j < list.size(); j++) {

                file = (File)list.get(j);

                abspath = file.getAbsolutePath().replace(File.separatorChar, '/');

                // 获取最后修改时间  

                long long_file_time = file.lastModified();

                if (!comperTime(Long.valueOf(long_file_time))) {

                  continue;

                }

                if (

                IsSrcFile(abspath.toLowerCase())

                )//java 文件  xml  文件

               

                {

                  System.out.println("修改的文件:" +  abspath); 

                  String path = this.directory + "/" + this.output + abspath.substring(str.length());

                  int index = path.lastIndexOf(".");

                  

                 String aterStr = abspath.substring(abspath.lastIndexOf("."));

                  

                  //获取后缀 

                  if(abspath.endsWith(".java")){

                 path = path.substring(0, index) + ".class";

                  }else{

                 

                 path = path.substring(0, index) + aterStr ;

                  }

                  

                  

                  

                  copy(path);

                  f = new File(path);

                  String name = f.getName();

                  int inex = name.lastIndexOf(".");

                  name = name.substring(0, inex);

                  List m = innerclass(f);

                  for (int k = 0; k < m.size(); k++) {

                    f = (File)m.get(k);

                    copy(f.getAbsolutePath());

                  }

                  if (!this.containsSrc){

                 continue;

                  }

                  // 复制src文件 

                  copySrcFile(abspath, (String)this.src.get(i));

                }

                else

                {

                  if (!comperTime(Long.valueOf(long_file_time)))

                    continue;

                  String path = this.directory + "/" + this.output + abspath.substring(str.length());

                  copy(path);

                }

              }

            }

          }

        }

        f = new File(this.directory + "/" + this.web_root_folder);

        list = getSubFiles(f);

        for (int i = 0; i < list.size(); i++) {

          f = (File)list.get(i);

          String path = f.getAbsolutePath().replace(File.separatorChar, '/');

          if (path.indexOf(this.directory + "/" + this.output) <= -1) {

            long long_file_time = f.lastModified();

            if (!comperTime(Long.valueOf(long_file_time)))

              continue;

            copy(path);

          }

        }

      }

      catch (Exception e) {

        msg("解析应用程序配置文件出错:" + e.getMessage(), 1);

      }

      long end = System.currentTimeMillis();

      System.out.println("共用 " + (end - this.start) + "毫秒");

      

      String text = "本次总更新文件数 " + this.sumcount + ",成功更新文件数 " + this.successcount ;

      System.out.println(text);

      

      msg("本次总更新文件数 " + this.sumcount + ",成功更新文件数 " + this.successcount);

      try {

        if (this.successcount > 0)

          Runtime.getRuntime().exec("explorer.exe " + this.outputdirectory.replace('/', File.separatorChar));

      } catch (IOException e) {

        msg("请手动查看输出目录");

      }

    }

  }

  public boolean copy(String path)

  {

    this.sumcount += 1;

    path = path.replace(File.separatorChar, '/');

    String newpath = null;

    if (this.containsSrc)

      newpath = this.outputdirectory + "/" + this.projectName + "/" + this.web_root_folder + path.substring(this.directory.length() + this.web_root_folder.length() + 1);

    else

      newpath = this.outputdirectory + "/" + this.projectName + path.substring(this.directory.length() + this.web_root_folder.length() + 1);

    File f = new File(path);

    File ff = new File(newpath);

    System.out.println(newpath);

    boolean bool = copyFile(f, ff);

    if (bool)

      this.successcount += 1;

    return bool;

  }

  public boolean copySrcFile(String path, String srcName)

  {

    this.sumcount += 1;

    path = path.replace(File.separatorChar, '/');

    String newpath = this.outputdirectory + "/" + this.projectName + "/" + srcName + path.substring(this.directory.length() + srcName.length() + 1);

    File f = new File(path);

    File ff = new File(newpath);

   // System.out.println(newpath);

    boolean bool = copyFile(f, ff);

    if (bool)

      this.successcount += 1;

    return bool;

  }

  public boolean comperTime(Long l)

  {

    boolean flag = false;

    if ((this.bool_starttime) && (this.long_starttime > l.longValue())) {

      return flag;

    }

    if ((this.bool_endtime) && (this.long_endtime < l.longValue()))

      return flag;

    return !flag;

  }

  public List<File> innerclass(File file)

  {

    int pos = file.getName().lastIndexOf(".");

    String shortname = file.getName().substring(0, pos);

    File parent = file.getParentFile();

    List list = new ArrayList();

    if ((parent.exists()) && (parent.isDirectory())) {

      File[] flist = parent.listFiles();

      File f = null;

      for (int i = 0; i < flist.length; i++) {

        f = flist[i];

        int index = f.getName().indexOf(shortname + "$");

        if (index == 0)

          list.add(f);

      }

    }

    return list;

  }

  public static ArrayList<File> getSubFiles(File baseDir)

  {

    ArrayList ret = new ArrayList();

    if (baseDir.exists()) {

      File[] tmp = baseDir.listFiles();

      if (tmp != null) {

        for (int i = 0; i < tmp.length; i++) {

          if ((tmp[i].isFile()) && (!tmp[i].isHidden())) {

            ret.add(tmp[i]);

          }

          if ((tmp[i].isDirectory()) && (!tmp[i].isHidden())) {

            ret.addAll(getSubFiles(tmp[i]));

          }

        }

      }

      tmp = (File[])null;

      return ret;

    }

    return null;

  }

  public static boolean copyFile(File oldFile, File newFile)

  {

    boolean flag = false;

    try {

      File f = new File(newFile.getParent());

      if (!f.exists())

        f.mkdirs();

      long l = oldFile.lastModified();

      FileInputStream input = new FileInputStream(oldFile);

      FileOutputStream output = new FileOutputStream(newFile);

      int len = 0;

      byte[] buffer = new byte[1024];

      while ((len = input.read(buffer)) != -1) {

        output.write(buffer, 0, len);

      }

      input.close();

      output.flush();

      output.close();

      newFile.setLastModified(l);

      if (newFile.exists())

        flag = true;

    } catch (FileNotFoundException e) {

      e.printStackTrace();

    } catch (IOException e) {

      e.printStackTrace();

    } catch (Exception e) {

      e.printStackTrace();

    }

    return flag;

  }

  public void readClassPath()

    throws Exception

  {

 initWebProject();

    InputStream is = new FileInputStream(this.directory + "/.classpath");

    SAXBuilder sb = new SAXBuilder();

    Document doc = sb.build(is);

    XPath xpath = XPath.newInstance("//classpath/classpathentry[@kind='src']");

    List list = xpath.selectNodes(doc);

    Element ele = null;

    for (int i = 0; i < list.size(); i++) {

      ele = (Element)list.get(i);

      this.src.add(String.valueOf(ele.getAttributeValue("path").replace(File.separatorChar, '/')));

    }

    xpath = XPath.newInstance("//classpath/classpathentry[@kind='output']");

    list = xpath.selectNodes(doc);

    if ((list != null) && (list.size() > 0)) {

      ele = (Element)list.get(0);

      this.output = ele.getAttributeValue("path").replace(File.separatorChar, '/');

      if(!isWebProject){

          this.web_root_folder = web_root_folder;

      }else{

     int index = this.output.lastIndexOf("/WEB-INF/classes");

          this.web_root_folder = this.output.substring(0, index);

      }

    }

  }

  /**

   * 初始验证是否web项目

   * @throws Exception

   */

  public void  initWebProject()

  throws Exception

{

  InputStream is = new FileInputStream(this.directory + "/.classpath");

  SAXBuilder sb = new SAXBuilder();

  Document doc = sb.build(is);

  XPath xpath = null;

 // XPath xpath = XPath.newInstance("//classpath/classpathentry[@kind='src']");

  List list =null ;

  Element ele = null;

  xpath = XPath.newInstance("//classpath/classpathentry[@kind='output']");

  list = xpath.selectNodes(doc);

  if ((list != null) && (list.size() > 0)) {

    ele = (Element)list.get(0);

    this.output = ele.getAttributeValue("path").replace(File.separatorChar, '/');

    if(this.output.indexOf("bin")>-1){

    output = "bin";

    web_root_folder = "bin";

    isWebProject = false;

    } 

  }

}

  public void validate()

  {

/////////验证是否为web项目 

    try

    {

      initWebProject();

      File f = null;

      Date date = null;

      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      if ("".equals(this.text_directory.trim())) {

        msg("项目目录不能为空");

        this.bool = false;

        return;

      }

      if ("".equals(this.text_outputdirectory.trim())) {

        msg("输出目录不能为空");

        this.bool = false;

        return;

      }

      f = new File(this.text_directory + "/" + ".classpath");

      if (!f.exists()) {

        msg("项目目录无效");

        this.bool = false;

        return;

      }

      f = f.getParentFile();

      this.directory = f.getAbsolutePath().replace(File.separatorChar, '/');

      this.projectName = f.getName();

      f = new File(this.text_outputdirectory);

      if ((!f.exists()) && (!f.isDirectory())) {

        msg("输出目录无效");

        this.bool = false;

        return;

      }

      f = new File(this.text_outputdirectory + "/updatetool");

      f.mkdirs();

      if (!f.exists()) {

        msg("输出目录无法操作");

        this.bool = false;

        return;

      }

      del(this.text_outputdirectory + "/updatetool");

      f.mkdirs();

      this.outputdirectory = f.getAbsolutePath().replace(File.separatorChar, '/');

      if (this.outputdirectory.indexOf(this.directory) > -1) {

        msg("输出目录选择错误", 1);

        this.bool = false;

        return;

      }

      if (!"".equals(this.text_starttime.trim())) {

        try {

          date = format.parse(this.text_starttime.trim());

          this.long_starttime = date.getTime();

          this.bool_starttime = true;

        } catch (ParseException e) {

          msg("开始时间格式不符合要求", 1);

          this.bool = false;

          return;

        }

      }

      if (!"".equals(this.text_endtime.trim())) {

        try {

          date = format.parse(this.text_endtime.trim());

          this.long_endtime = date.getTime();

          this.bool_endtime = true;

        } catch (ParseException e) {

          msg("结束时间格式不符合要求", 1);

          this.bool = false;

          return;

        }

      }

      if ((this.bool_starttime) && (this.bool_endtime) && (this.long_starttime > this.long_endtime)) {

        msg("开始时间晚于结束时间", 1);

        this.bool = false;

        return;

      }

      if ((!this.bool_starttime) && (!this.bool_endtime)) {

        msg("时间范围不能全部为空", 1);

        this.bool = false;

        return;

      }

      

      ////////////////////////////////////////////////////////////////////////////////////

      

      

    }

    catch (Exception e) {

    e.printStackTrace();

   

      msg("验证发生错误:" + e.getMessage(), 1);

      this.bool = false;

      return;

    }

    this.bool = true;

  }

  public static void del(String filepath)

    throws IOException

  {

    File f = new File(filepath);

    if ((f.exists()) && (f.isDirectory())) {

      if (f.listFiles().length == 0) {

        f.delete();

      } else {

        File[] delFile = f.listFiles();

        int i = f.listFiles().length;

        for (int j = 0; j < i; j++) {

          if (delFile[j].isDirectory()) {

            del(delFile[j].getAbsolutePath());

          }

          delFile[j].delete();

        }

        delFile = (File[])null;

      }

    } else if ((f.exists()) && (!f.isDirectory())) {

      f.delete();

    }

    f = null;

  }

  public void msg(String msg, int icon)

  {

   /* MessageBox box = new MessageBox(this.shell, icon);

    box.setText("消息");

    box.setMessage(msg);

    box.open();*/

  }

  public void msg(String msg)

  {

    msg(msg, 2);

  }

  public static void main(String[] args) throws Exception 

  {

 // 设置目录 及其文件路径 

 // 项目路径  输出路径 

//  String text_directory = "F:\\work\\工作整理-xiaohua\\项目资料归档\\小项目\\提取工具\\源码\\MyUpdateTool"; // 文件目录

  

 String text_directory = "C:\\Users\\sqh\\Workspaces\\MyEclipse 8.5\\WebPro" ;

  String text_outputdirectory = "D:\\updatetool";// 输出目录 

  String text_starttime ="2016-06-06 00:00:00";// 开始时间  

  String text_endtime = "2016-06-07 00:00:00"; // 结束时间 

  boolean containsSrc = true ;//是否包含源码   false 不包含源码 

  

  String configName ="java,xml,properties" ;// 配置 提取的文件 

  

  MyToolApp app = new MyToolApp( text_directory ,  text_outputdirectory , 

   text_starttime , text_endtime , containsSrc , configName);

  // 查询文件 

  app.search();

  }

  public MyToolApp(){

  }

  /***

   * 初始化工具 

   * @param text_directory   项目路径 

   * @param text_outputdirectory 输出目录 

   * @param text_starttime   开始时间 

   * @param text_endtime 结束时间 

   * @param containsSrc false 不包含源码  true 包含源码

   */

  public MyToolApp(String text_directory , String text_outputdirectory , 

 String  text_starttime ,String text_endtime ,boolean containsSrc,

 String configName 

  ){

 logger.info(" init MyToolApp   ") ;

 this.text_directory = text_directory ;

 this.text_outputdirectory =  text_outputdirectory ;

 this.text_starttime = text_starttime ;

 this.text_endtime = text_endtime ;

 this.containsSrc = containsSrc ;

 this.configName = configName ;// 配置 提取的文件 

 this.directory = text_directory ;

  }

  /**

   * 验证是否为src的配置文件 

   * @param fileName

   * @return

   */

  public boolean  IsSrcFile(String fileName){

 boolean flag = false;

 String appStr = null;

 if(fileName!=null && !fileName.equals("")){

 appStr = fileName.substring(fileName.lastIndexOf(".")+1);

 if(configName.indexOf(appStr)>-1){

 flag = true;

 }

 }

 return flag;

  }

  

}

猜你喜欢

转载自sqh-me1232008.iteye.com/blog/2303401
今日推荐