java解压zip文件,读取txt文件

之前需求是将一个txt文件和word文件打包成zip文件,接下来的要求是将zip文件解压,读取其中txt文件,并将word文件复制到指定路径。
写代码首先目的要明确,这里我是三步走战略。
1.先解压zip文件,分别获取里面的txt文件和word文件。
2.读取txt文件,将word文件复制到服务器指定路径。
3.将解压的文件删除。
说实话这个需求写的时候一直不理解他的意义在哪里,不过既然要求了那就整吧。顺便可以将这几步操作记录下来以便日后使用

	   public void importNetCase() {
	    	try {
	    		Employee emp = (Employee) getSession().getAttribute(
	    				MyConstants.loginEmployee);
	    		NetEventCase nec = new NetEventCase();
	    		
	    		nec.setAdder(emp.getEmployeeGuid());
	    		nec.setAddTime(new Date());
	    		nec.setAdderName(emp.getEmployeeName());
	    		
	    		//获取zip文件
	    		File caseFile = this.getCaseFile();
	    		String realPath = SystemParamConfigUtil.getParamValueByParam("basepath");
	    		//解压zip文件
	    		List<String> returnlist = upzipFile(caseFile,realPath);
	    		String txtFileName = "";
	    		String docFileName = "";
	    		//判断是txt文件还是其他文件
	    		for(String file:returnlist){
	    			String end = file.substring(file.length()-3, file.length());
	    			if(end.equals("txt")){
	    				txtFileName = file;
	    			}else{
	    				docFileName = file;
	    			}
	    		}
	    		File docFile = new File(docFileName);
	    		File txtFile = new File(txtFileName);
	    		
	    		// 读取txt文件中的内容
	    		String txt = readStringFromtxt(txtFileName);
	    		if(null != txt){
	    		String[] a = txt.split(",");	    		
	    			nec.setCaseTitle(a[1]);
	    			nec.setColId(a[0]);
	    			
	    		}
	    		if(docFile!=null){
	    			
	    			//String realPath = SystemParamConfigUtil.getParamValueByParam("fileLocation");
	    			String caseFileFileName = docFileName;
	    			String dstPath = MyUtils.getRealFilePath(caseFileFileName,realPath); // 得到上传文件在服务器上存储的唯一路径,并创建存储目录
	    			File dstFile = new File(realPath + dstPath);
	    			// 复制文件
	    			MyUtils.copy(docFile, dstFile);// 完成上传文件,就是将本地文件复制到服务器上
	    			nec.setFileAddr(dstPath);
	    			nec.setFileName(caseFileFileName);
	    			//String ofdPath =  uploadfilename.substring(0,uploadfilename.lastIndexOf("."))+".ofd";
	    			String ofdPath = dstPath.substring(0,dstPath.lastIndexOf("."))+".ofd";
	    			String trueOfdPath = realPath + ofdPath;//.replace("\\\\", "/")
	    			nec.setOfdAddr(ofdPath);
	    			//文件转ofd
				/*	try{
						OfficeToOfdThread ofd = new OfficeToOfdThread(realPath + dstPath,realPath + ofdPath);
						ofd.start();
					}catch(Exception ex){
						System.out.println("pdf转ofd失败");
					}*/
	    		}
	    		netEventService.addNetEventCase(nec);
	    		
	    		//删除解压的文件
	    		deleteFile(docFileName);
	    		deleteFile(txtFileName);
	    		
	    		toPage("success");
	    	} catch (Exception e) {
	    		toPage("error");
	    		e.printStackTrace();
	    	}
	    }

上面是总体战略,接下来是各项细节操作
解压zip文件,返回其中文件名


/**
     *网络舆情栏目
     * zipName:要解压缩的文件
     * targetDirName:指定解压路径
     */
public List upzipFile(File zipName, String targetDirName) {
		if (!targetDirName.endsWith(File.separator)) {
			targetDirName += File.separator;
		}
		List<String> NameList = new ArrayList<String>();
		try {
			// 根据zip文件创建ZipFile对象,此类的作用是从zip文件读取条目
			ZipFile zipFile = new ZipFile(zipName);
			ZipEntry zn = null;
			String entryName = null;
			String targetFileName = null;
			byte[] buffer = new byte[4096];
			int bytes_read;
			Enumeration entrys = zipFile.entries();			// 获取ZIP文件里所有的文件条目的名字
			while (entrys.hasMoreElements()) {				// 循环遍历所有的文件条目的名字
				zn = (ZipEntry) entrys.nextElement();
				entryName = zn.getName();				// 获得每一条文件的名字
				targetFileName = targetDirName + entryName;
				if (zn.isDirectory()) {					
					new File(targetFileName).mkdirs();		// 如果zn是一个目录,则创建目录
					continue;
				} else {					
					new File(targetFileName).getParentFile().mkdirs();// 如果zn是文件,则创建父目录
				}				
				File targetFile = new File(targetFileName);	// 否则创建文件
				System.out.println("正在创建文件:" + targetFile.getAbsolutePath());	
				String returnName = targetFile.getAbsolutePath();
				FileOutputStream os = new FileOutputStream(targetFile);// 打开文件输出流
				InputStream is = zipFile.getInputStream(zn);	// 从ZipFile对象中打开entry的输入流
				NameList.add(returnName);
				while ((bytes_read = is.read(buffer)) != -1) {
					os.write(buffer, 0, bytes_read);
				}		
				os.close();								// 关闭流
				is.close();
			}
			System.out.println("解压缩"+zipName+"成功!");
		} catch (IOException err) {
			System.err.println("解压缩"+zipName+"失败: " + err);
		}
		return NameList;
	}

读取txt文件中的内容

 	// 读取txt文件
 	// txtpath文件名
		public static String readStringFromtxt(String txtpath) {
			File file = new File(txtpath);
			StringBuilder result = new StringBuilder();
			try {
				BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); 
				String s = null;
				while ((s = br.readLine()) != null) {
					result.append(s);
				}
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result.toString();
		}

复制文件到指点文件夹

	/**
	 * 自己封装的一个把源文件对象复制成目标文件对象,以完成文件上传
	 * src:源文件
	 * dst:目标文件
	 */
	public static void copy(File src, File dst) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(dst),
					BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

删除文件

// pathname:文件路径
public static void deleteFile(String pathname){
			boolean result = false;
			File file = new File(pathname);
			if (file.exists()) {
				file.delete();
				result = true;
				System.out.println("文件已经被成功删除");
			}
		}

要注意的是,我这里通过File file = new File(pathname);获取的文件,都是绝对路径+文件名的方式获取文件,不然的话也可以通过getAbsolutePath():方法返回抽象路径名的绝对路径名字符串。


版权声明:本文为weixin_43805637原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。