Spring:如何解析上传的zip文件?

时间:2012-06-13 13:43:21

标签: java spring zip zipinputstream

我将 zip 存档上传到服务器,并希望在其中打开.txt.jpg个文件。我在Controller中成功获取了存档,并通过ZipEntry获取了每个文件的名称。现在我想打开它,但为此我应该得到一个完整的路径到我的文件。

我还没有找到如何做到这一点。你能建议一些方法怎么做?

更新

我尝试使用下面建议的示例,但我无法打开文件

ZipFile zFile = new ZipFile("trainingDefaultApp.zip");

我有FileNotFoundException

所以我回到了我的起点。我在Java Spring应用程序中上传了表单。在控制器中,我有一个zip存档byte[]

@RequestMapping(method = RequestMethod.POST)
public String create(UploadItem uploadItem, BindingResult bindingResult){
    try {
        byte[] zip = uploadItem.getFileData().getBytes();
        saveFile(zip);

然后我得到了每个ZipEntry

    InputStream is = new ByteArrayInputStream(zip);
    ZipInputStream zis = new ZipInputStream(is);

    ZipEntry entry = null;
    while ((entry = zis.getNextEntry()) != null) {
        String entryName = entry.getName();
        if (entryName.equals("readme.txt")) {
            ZipFile zip = new ZipFile(entry.getName()); // here I had got an exception

根据文档,我做得很好,但对我来说,仅传递文件名并怀疑你成功打开文件是很奇怪的

2 个答案:

答案 0 :(得分:1)

zipFile.getInputStream(ZipEntry entry)将返回特定条目的输入流。

查看ZipFile.getInputStream() - javadocshttp://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipFile.html#getInputStream(java.util.zip.ZipEntry)

<强>更新

我误解了你的问题。对于使用ZipInputStream,Oracle网站(http://java.sun.com/developer/technicalArticles/Programming/compression/)上有示例代码,向您展示如何从流中读取。请参阅第一个代码示例:代码

  • 示例1:UnZip.java。

在此处复制,它正在从条目中读取并将其直接写入文件,但您可以用您需要的任何逻辑替换它:

ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
   System.out.println("Extracting: " +entry);
   int count;
   byte data[] = new byte[BUFFER];
   // write the files to the disk
   FileOutputStream fos = new FileOutputStream(entry.getName());
   dest = new 
   BufferedOutputStream(fos, BUFFER);

   while ((count = zis.read(data, 0, BUFFER)) != -1) {
        dest.write(data, 0, count);
   }
}

答案 1 :(得分:0)

我解决了我的问题。解决方案直接与ZipInputStream一起工作。代码如下:

    private void saveFile(byte[] zip, String name, String description) throws IOException {
    InputStream is = new ByteArrayInputStream(zip);
    ZipInputStream zis = new ZipInputStream(is);

    Application app = new Application();
    ZipEntry entry = null;
    while ((entry = zis.getNextEntry()) != null) {
        String entryName = entry.getName();
        if (entryName.equals("readme.txt")) { 
           new Scanner(zis); //!!!
           //... 
           zis.closeEntry();
相关问题