JAVA读取压缩包并上传文件

本文介绍了一个Java实现的压缩包上传示例,通过Struts框架处理HTTP请求,利用Apache Commons库解压并保存文件。

 一个Java读取压缩包并上传文件 例子

 

package com.bsteel.newbase.admin.uploadfile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import com.bsteel.newbase.admin.uploadfile.form.UpLoadFileForm;
import com.bsteel.rscenter.util.Constants;

public class UpLoadFileAction extends Action {
	protected Log log = LogFactory.getLog(getClass());
	private static final String filePath = "/WEB-INF/classes/config/config.properties";

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UpLoadFileForm uploadfileform = (UpLoadFileForm) form;
		if (StringUtils.defaultString(uploadfileform.getJSP_PATH()).equals(
				"upload")) {
			if (uploadfileform.getUpLoadFileName() == null
					|| uploadfileform.getTemplate() == null
					|| "".equals(uploadfileform.getUpLoadFileName())
					|| "".equals(uploadfileform.getTemplate())) {
				request.setAttribute("showok", "0");
				return mapping.findForward("success");
			}
			// 读取文件信息
			System.out.println("uploadfileform.getTheFile()="
					+ uploadfileform.getUpLoadFileName());
			FormFile theFile = uploadfileform.getUpLoadFileName();
			// 判断上传文件类型及规定"cbf"
			String fileName = theFile.getFileName();
			int pos = fileName.lastIndexOf(".");
			String postfix = fileName.substring(pos + 1).trim();
			String cbfstr = fileName.substring(0, 3).trim();
			System.out.println("postfix=" + postfix);
			if (!postfix.equalsIgnoreCase(Constants.FILE_ZIP)
					|| !cbfstr.equals("cbf")) {
				request.setAttribute("showok", "1");
				return mapping.findForward("success");
			} else {
				// 备份原有文件
				removeFiles(uploadfileform.getTemplate());
				// 上传文件
				try {
					String[] path = loadConfig();
					unzip(theFile, path[0], uploadfileform.getTemplate());
					request.setAttribute("showok", "2");
					log.info("文件上传成功!");
				} catch (Exception e) {
					log.info("上传文件失败:" + e.getMessage());
				}
			}
		}
		return mapping.findForward("success");
	}

	/**
	 * 读取资源文件
	 * 
	 * @return
	 */

	private String[] loadConfig() {

		Properties config = new Properties();
		String[] properties = new String[2];
		try {
			InputStream is = getClass().getResourceAsStream(filePath);
			if (is == null) {
				return null;
			} else {
				config.load(is);
				properties[0] = config.getProperty("datapath");
				properties[1] = config.getProperty("bakpath");
			}
			return properties;
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 
	 * 备份同类型文件
	 */

	private void removeFiles(String str) {
		SimpleDateFormat formatDate = new SimpleDateFormat("yyMMdd");
		String[] path = loadConfig();
		File f = new File(path[0]);
		if (f.exists()) {
			File[] fileList = f.listFiles();
			for (int i = 0; i < fileList.length; i++) {
				String filename = fileList[i].getName();
				int beginInt = filename.indexOf("_") + 1;
				int endInt = filename.indexOf(".");
				if (filename.substring(beginInt, endInt).equals(str)) {
					fileList[i].renameTo(new File(path[1]
							+ fileList[i].getName()
							+ formatDate.format(new Date()) + ".bak"));
					log.info("remove file ->" + fileList[i].getName());
				}
			}
		}
	}

	/**
	 * 
	 * 上传zip文件
	 */

	public void unzip(FormFile thefile, String outputDirectory, String str) {
		try {
			ZipInputStream in = new ZipInputStream(thefile.getInputStream());
			ZipEntry z = in.getNextEntry();
			while (z != null) {
				String zipsName = z.getName();
				// 提取压缩包中的xml文件
				int pos = zipsName.lastIndexOf(".");
				String postXml = zipsName.substring(pos + 1).trim();
				if (postXml.equalsIgnoreCase(Constants.FILE_XML)) {
					File f = new File(outputDirectory);
					f.mkdir();
					if (z.isDirectory()) {
						f = new File(outputDirectory + "documents_" + str + "."
								+ Constants.FILE_XML);
						f.mkdir();
					} else {
						f = new File(outputDirectory + "documents_" + str + "."
								+ Constants.FILE_XML);
						f.createNewFile();
						FileOutputStream out = new FileOutputStream(f);
						int b;
						while ((b = in.read()) != -1) {
							out.write(b);
						}
						out.close();
					}
					// 读取下一个ZipEntry
					z = in.getNextEntry();
				}
			}
			in.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 文章引自:http://blog.163.com/yangjuqi@126/blog/static/28452285200791192638761/

如果上传文件是MultipartFile类型,首先需要把它转换成File类型,然后再使用上面提到的方式来读取RAR文件。 下面是一个示例代码: ```java import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.rar.RarArchiveInputStream; import org.springframework.web.multipart.MultipartFile; import java.io.*; public class RarReader { public static void main(String[] args) throws IOException, ArchiveException { MultipartFile rarFile = ...; // 从请求参数中获取MultipartFile File tempFile = File.createTempFile("temp", ".rar"); rarFile.transferTo(tempFile); FileInputStream fileInputStream = new FileInputStream(tempFile); ArchiveInputStream archiveInputStream = new RarArchiveInputStream(fileInputStream); ArchiveEntry archiveEntry; while ((archiveEntry = archiveInputStream.getNextEntry()) != null) { if (!archiveEntry.isDirectory()) { String fileName = archiveEntry.getName(); System.out.println("Reading file: " + fileName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = archiveInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } byte[] fileContent = outputStream.toByteArray(); // TODO: 处理文件内容 } } archiveInputStream.close(); fileInputStream.close(); tempFile.delete(); } } ``` 这个示例代码首先将MultipartFile类型的文件保存到临时文件中,然后再使用上面提到的方式来读取RAR文件。注意,在读取完RAR文件后,需要删除临时文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值