`
SavageGarden
  • 浏览: 215252 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

超级简单、超级实用的版本升级小工具----代码实现

    博客分类:
  • Java
阅读更多

接上篇

webserver使用的是resin3.1.9,首先在web.xml中配置invoker方式来处理请求

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <classpath id='WEB-INF/classes'
             source='WEB-INF/src'
             compile='false'/>
  <classpath id='WEB-INF/lib' library-dir='true'/>
  <servlet-mapping url-pattern='/servlet/*' servlet-name='invoker'/>
</web-app>

 

然后写一个search.jsp,选择开始、结束日期后,将提交到UpdateServlet来处理

<form name="form" method="post" action="/servlet/com.swfml.update.action.UpdateServlet">
......
</form>

 然后来写UpdateServlet,根据不同的action执行不同的操作

public void doPost(HttpServletRequest request, HttpServletResponse response) {
		String defaultAction = "";
		String url = actionMap(request, response, defaultAction);
		if ((url.length() > 0) && (!response.isCommitted())) {
            try {
				response.sendRedirect(URLDecoder.decode(url));
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}
 
private String actionMap(HttpServletRequest request, HttpServletResponse response, String defaultAction) {
		String action = defaultAction;
		String url = "";
		if ((request.getParameter("action") != null) && (request.getParameter("action").length() > 0)) {
			action = request.getParameter("action").trim();
        }
		if(action.equals("search")) {
			doSearch(request, response);
		} else if(action.equals("create")) {
			doCreate(request, response);
		} else if(action.equals("upload")){
			doUpload(request, response);
		} else if(action.equals("unzip")){
			doUnzip(request, response);
		} else if(action.equals("update")){
			doUpdate(request, response);
		} 
		return url;
	}
 

然后来处理检索

private void doSearch(HttpServletRequest request,
			HttpServletResponse response) {
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String searchDir = getServletContext().getRealPath("/");
		searchDir = searchDir.substring(0, searchDir.length() - 1);
		ArrayList updateFileList = ProUpdate.searchFile(searchDir, startDate, endDate);
		request.setAttribute("updateFileList", updateFileList);
		request.getSession().setAttribute("updateFileList", updateFileList);
		request.setAttribute("updateMessage", ProUpdate.updateMessage);
		try {
			RequestDispatcher rd = request.getRequestDispatcher("/update/search.jsp");
			rd.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 

其它处理类似,包含的功能有:

文件检索、生成zip包,解压zip包、备份替换文件、servlet实现上传下载

 

生成zip包

/**
	 * 将更新文件列表打包到输出文件
	 * @param outFile
	 * @param updateFileList
	 * @throws FileNotFoundException
	 */
	public static void createZip(String zipFile, ArrayList updateFileList) throws FileNotFoundException {
		String searchDir = getSearchDir(updateFileList);
		File outfile;
		if(zipFile.length() > 0) {
			outfile = new File(zipFile);
		} else {
			outfile = new File(updateFile);
		}
		ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(outfile));
		byte[] b = new byte[1024];
		int read = 0;
		StringBuffer strBuffer = new StringBuffer();
		try {
			for(int i = updateFileList.size() - 1; i >=0; i --) {
				
				File file = (File)updateFileList.get(i);
				String filePath = "";
				if(file.getPath().length() > searchDir.length()) {
					filePath = file.getPath().substring(searchDir.length() + 1) + (file.isDirectory() ? "/" : "");
				} else {
					filePath = "/";
				}
				filePath = filePath.replace('\\', '/');
				if(!pathIsExit(filePath)) {
					outputStream.putNextEntry(new ZipEntry(filePath));
				}
				if(file.isFile()) {
					strBuffer.append("/" + filePath + "\r\n");
					FileInputStream inputStream = new FileInputStream(file);
					while((read = inputStream.read(b)) != -1) {
						outputStream.write(b, 0, read);
					}
					inputStream.close();
				}
			}
			outputStream.putNextEntry(new ZipEntry(msgFileName));
			outputStream.write(strBuffer.toString().getBytes());
			outputStream.closeEntry();
			printZipMessage(outfile.getPath());
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

 解压zip包

/**
	 * 解压文件到指定目录
	 * @param zipFilePath
	 * @throws FileNotFoundException
	 */
	public static String unZip(String outputPath, String zipFilePath) throws FileNotFoundException {
		ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFilePath));
		ZipEntry entry;
		Date date = new Date();
		if(outputPath.length() > 0) {
			outputDir = outputPath;
		}
		outputDir = outputDir + File.separator + timeDateFormat.format(date);
		File outputFile = new File(outputDir);
		outputFile.mkdirs();
		String updateMesaage = outputDir + "!";
		try {
			while((entry = inputStream.getNextEntry()) != null) {
				if(entry.isDirectory()) {
					File file = new File(outputDir + File.separator + entry.getName().substring(0, entry.getName().length() - 1));
					file.mkdirs();
				} else {
					File file = new File(outputDir + File.separator + entry.getName());
					System.out.println(file.getPath());
					if(!file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					file.createNewFile();
					FileOutputStream outputStream = new FileOutputStream(file);
					byte[] b = new byte[1024];
					int read = 0;
					while((read = inputStream.read(b)) != -1) {
						outputStream.write(b, 0, read);
					}
					outputStream.close();
					if(file.getName().equals(msgFileName)) {
						BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
						String s = "";
						while((s = reader.readLine()) != null) {
							updateMesaage += s + "#";
						}
					}
				}
			}
			inputStream.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
		return updateMesaage;
	}

 下载更新包

/**
	 * 生成更新包
	 * @param request
	 * @param response
	 */
	private void doCreate(HttpServletRequest request,
			HttpServletResponse response) {
		ArrayList updateFileList = new ArrayList();
		String zipFile = getServletContext().getRealPath("/") + File.separator + "update.zip";
		if(request.getSession().getAttribute("updateFileList") != null) {
			updateFileList = (ArrayList)request.getSession().getAttribute("updateFileList");
			ProUpdate.createUpdateFile(zipFile, updateFileList);
		}
		response.setContentType("text/html");
		try {
			response.sendRedirect("/update.zip");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
 

上传更新包

/**
	 * 上传更新包
	 * @param request
	 * @param response
	 */
	private void doUpload(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			File updatefile = new File(getServletContext().getRealPath("/") + File.separator + "WEB-INF" + File.separator + "update" + File.separator + "update.zip");
			File tempFile = new File(getServletContext().getRealPath("/") + File.separator + "WEB-INF" + File.separator + "update" + File.separator + "update.temp.txt");
			if(!tempFile.exists()) {
				tempFile.createNewFile();
			}
			RandomAccessFile raFile = new RandomAccessFile(tempFile, "rw"); 
			ServletInputStream inputStream = request.getInputStream();
			FileOutputStream outputStream = new FileOutputStream(updatefile);
			byte[] b = new byte[1024];
			int read = 0;
			while((read = inputStream.read(b)) != -1) {
				raFile.write(b, 0, read);
			}
			inputStream.close();
			raFile.close();
			raFile = new RandomAccessFile(tempFile, "r"); 
			String startFlag = raFile.readLine();
			String endFlag = startFlag + "--";
			String line = null;
			raFile.seek(0);
			long startIndex = 0;
			long endIndex = 0;
			while((line = raFile.readLine()) != null) {
				if(line.equals(startFlag) && !line.equals(endFlag)) {
					startIndex = raFile.getFilePointer() - (startFlag.length() + 2);
				} else if(line.equals(endFlag)){
					endIndex = raFile.getFilePointer() - (endFlag.length() + 2);
				}
			}
			raFile.seek(0);
			raFile.seek(startIndex);
			raFile.readLine();
			raFile.readLine();
			raFile.readLine();
			raFile.readLine();
			while(raFile.getFilePointer() < endIndex) {
				outputStream.write(raFile.readByte());
			}
			outputStream.close();
			raFile.close();
			if(tempFile.exists()) {
				tempFile.delete();
			}
			request.setAttribute("updatefilepath", updatefile.getPath());
			RequestDispatcher rd = request.getRequestDispatcher("/update/uploadResult.jsp");
			rd.forward(request, response);
		} catch(Exception e) {
			e.printStackTrace();
		}
		
	}
 

具体请参见代码,欢迎拍砖!

 

 

分享到:
评论
4 楼 SavageGarden 2010-03-01  
ahpo 写道
很不错的收藏了,项目中应该会很有用,楼主是这是历年项目经验啊。

惭愧,惭愧
3 楼 SavageGarden 2010-03-01  
whiteface999 写道
项目中也需要类似的东西,感谢楼主啊。过滤的地方可以改进一下。
File[] files = rootDir.listFiles(getFileRegexFilter("\\.svn"));
public static FilenameFilter getFileRegexFilter(String regex) {  
        final String regex_ = regex;  
        return new FilenameFilter() {  
            public boolean accept(File file, String name) {  
                boolean ret = name.matches(regex_);   
                return !ret;  
            }  
        };  
    }

恩,这个工具的核心就是检索文件,所以想提高效率也就是在这里优化
2 楼 whiteface999 2010-02-26  
项目中也需要类似的东西,感谢楼主啊。过滤的地方可以改进一下。
File[] files = rootDir.listFiles(getFileRegexFilter("\\.svn"));
public static FilenameFilter getFileRegexFilter(String regex) {  
        final String regex_ = regex;  
        return new FilenameFilter() {  
            public boolean accept(File file, String name) {  
                boolean ret = name.matches(regex_);   
                return !ret;  
            }  
        };  
    }
1 楼 ahpo 2010-02-26  
很不错的收藏了,项目中应该会很有用,楼主是这是历年项目经验啊。

相关推荐

    天鹰超级卫士防火墙V2.92航母版【网桥版本】

    产品名称:天鹰超级卫士(Skeagle Super Guard) ------------------------------------------------------------------------------------ 【V2.91 Build2012112802 更新说明】-- 2012年11月28日 1. 新功能: 1.1 ...

    易语言程序免安装版下载

     此次重大版本升级不影响以前的源代码(.e)和模块(.ec)。只要代码或模块中未用到“不支持静态编译”的支持库、COM/OCX等,都可以静态编译。以前编译好的模块(.ec)甚至不需要重新编译即可直接支持静态编译。  支持库...

    E语言1000模块

    PC6.com 为您收集整理,小编找的不容易,大家多多支持啊。。 2008-11-08 14:41 文件夹 文件夹 易语言模块大全 2005-10-21 15:30 14489 3100 易语言模块大全\24位转...2005-08-15 09:49 8584 2916 易语言模块大全\代码...

    C++ 超级计算器 代码难度:难(计算器系列第三版完结)

    第二个版本会升级几个新运算,而第三个版本是全面升级,我决定加入一些其他的功能,预计有300多行。我就不说太多了,大家可以自己尝试,真的很不错!其实我写计算器还有个原因:就是暑假作业有的太难算了,家里...

    超级IE首页设置工具(不修改系统任何内容)

    1:修改首页可以通过修改C:\windows\system32\下的cw文件内容来实现(记事本打开)。 本软件运行环境需要net framework 2.0以上版本 使用方法: A:直接运行"浏览器辅助工具".exe &lt;本程序不修改系统任何东西,不像...

    易语言模块大全汇总批量下载

    2005-08-15 09:49 8584 2916 易语言模块大全\代码编辑器部分模块.ec 2002-11-07 18:42 100179 19092 易语言模块大全\仿WinXP窗口v3.1版.ec 2005-10-21 15:31 94979 18657 易语言模块大全\仿XP界面3.0特别版模块 3.0....

    入门学习Linux常用必会60个命令实例详解doc/txt

    -n:防止sync系统调用,它用在用fsck修补根分区之后,以阻止内核用老版本的超级块覆盖修补过的超级块。 -w:并不是真正的重启或关机,只是写wtmp(/var/log/wtmp)纪录。 -f:没有调用shutdown,而强制关机或...

    小狐狸CHATGPT智能问答AI创作系统v1.6.4 PHP源码

    当前全民热议,市场空白,风口项目,流量超级大,引流太简单!一键下单即可拥有自己的AI生产力工具! 小狐狸AI付费创作系统 (独立版+无限多开+完全开源+多端同步+分销+万能创作),本源码含有前后端,支持Web和小...

    1000个【易语言模块大全汇总批量下载】

    2005-08-15 09:49 8584 2916 易语言模块大全\代码编辑器部分模块.ec 2002-11-07 18:42 100179 19092 易语言模块大全\仿WinXP窗口v3.1版.ec 2005-10-21 15:31 94979 18657 易语言模块大全\仿XP界面3.0特别版模块 3.0....

    完美学校网站系统全站源代码学校网站模板下载

    增加其它一些实用小工具。 19:后台网站属性设置增加自定义Bottom菜单,是否开启注册用户签收功能。 20:初始化时可选择部份初始化,统计数据可以初始化。 21:全新的个人用户 博客 功能 22:全面支持RSS聚合...

    EXCEL必备工具箱EXCELtool.rar

    按界面提示可以轻松安装,安装后打开EXCEL/WPS,启动Excel或WPS表格程序工具栏中如果多出“工具箱"标签,就表明已经成功安装,以后升级时只需覆盖安装EXCEL必备工具箱,不需要先卸载工具箱旧版本。 4:每个功能都有...

    Access 2000数据库系统设计(PDF)---025

    543.4.1 系统默认值 553.4.2 数据表视图的默认值 583.5 使用Access帮助 593.5.1 上下文相关的帮助 593.5.2 “帮助”菜单 603.5.3 Microsoft Access的帮助窗口 613.5.4 “Office助手” 643.6 使用“数据库实用工具” ...

    安卓超级修改大师

    安卓修改大师可以让您轻松将任何APK安装包进行反编译,替换应用程序界面上的任何文字和图片,并且通过代码级别的修改,实现汉化、破解、功能增强,甚至可以在任何的界面添加自定义的代码和功能。本软件还提供多渠道...

    欧维涂鸦论坛美化版

    [+]PBBS\UpdatefixINC1.asp以前的版本升级到V2.1AC(sp2)的升级程序包含文件 [+]PBBS\UpdatefixINC2.asp以前的版本升级到V2.1AC(sp2)的升级程序包含文件 [+]PBBS\database\IPaddress_2big#.asa包含15万条IP记录为PB...

    Cornerstone_4.1破解版mac版SVN客户端

    Cornerstone for Mac 是一个强大的,面向用户的版本控制实用程序,构建在开源Subversion版本控制系统之上,使复杂的版本控制项目尽可能简单。此外,Cornerstone全面支持Subversion的所有丰富功能,同时具有极强的...

    沸腾展望新闻多媒体系统 v1.1 SP4 bulid 090410.rar

    增加其它一些实用小工具。 19:后台网站属性设置增加自定义Bottom菜单,是否开启注册用户签收功能。 20:初始化时可选择部份初始化,统计数据可以初始化。 Build2更新: 21:全新的个人用户博客功能 22:全面...

    EXCEL集成工具箱V6.0

    Excel集成工具箱6.0是利用VBA(Visual Basic for Applications)语言编写的增强应用型插件。包括160个菜单功能和100个左右 自定义函数,集160个工具于一身,但体积小于15MB。当安装集成工具箱后,如果您使用Excel ...

    游戏画面就弹出内存不能为read修复工具

    解决方法:这是对方利用QQ的BUG,发送特殊的代码,做QQ出错,只要打上补丁或升级到最新版本,就没事了。 该内存不能为read或written的解决方案关键词: 该内存不能为"read" 该内存不能为"written" 从网上搜索来的...

    AMR超级站群系统 v1.1.rar

    21.超级方便的广告管理:内置广告提取代码,可以匹配大约80%的广告位,用户只需要替换里面的广告代码,即可批量管理所有站群的广告位!此外,还可批量添加整个站群统一的广告位! 22.支持集群化部署,宕机自动切换:...

Global site tag (gtag.js) - Google Analytics