xiaoran1392010 2009-06-17 09:53
浏览 292
已采纳

java 关于解压rar文件 代码有点问题 帮改正

[color=red]问题:目前这个代码执行第一次的时候就可以解压rar文件,但是第二次就无效了。测试可以执行一次后servlet操作,删除解压后解压后的文件,在执行,rar文件就不解压了。我用的是tomcat服务器。 [/color]

文件1:UnrarServlet
代码
[code="java"]
package com.jh.upload.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

@SuppressWarnings("serial")
public class UnrarServlet extends HttpServlet {
private static String unrarCmd = "C:\Program Files\WinRAR\unrar x";

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doPost(request, response);
}

@SuppressWarnings( { "static-access", "deprecation" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("gbk");
    response.setContentType("text/html;charset=gbk");
    // 设置字符编码为UTF-8, 这样支持汉字显示
    response.setCharacterEncoding("gbk");

    //文件名 传进来或者取过来
    String file = "系统管理.rar";
    PrintWriter out = response.getWriter();

    String rarFileName = request.getRealPath("/test") + "\\" + file;
    String destDir = request.getRealPath("/test");

    File f = new File(rarFileName);
    if ((!f.exists()) && (f.length() <= 0)) {
        out.println("要解压的文件不存在!<p />");
        out.println("<a href='MyJsp.jsp' >返回</a>");
        return;
    }

    unrarCmd += " " + rarFileName + " " + destDir;
    try {
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec(unrarCmd);


        StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(),"ERROR");            
        errorGobbler.start();
        StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(),"STDOUT");
        //  kick  off  stdout  
        outGobbler.start();
        p.waitFor();

        System.out.println("进程:--"+p.exitValue());
    } catch (Exception e) {
        System.out.println(e.getMessage());

    }

    //判断目录是否存在
    String fileName = file.substring(0, file.lastIndexOf("."));

    File filePath = new File(destDir + "\\" + fileName);

    if (filePath.isDirectory()) {
        out.println("<p />解压成功!");
    } else {
        out.println("<p />解压失败,请手工解压!");
    }

    out.println("<p /><a href='MyJsp.jsp' >返回</a>");
    return;

}

}
[/code]
文件2:StreamGobbler.java
[code="java"]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

public class StreamGobbler extends Thread {
InputStream is;
String type;
OutputStream os;

StreamGobbler(InputStream is, String type) {
this(is, type, null);
}

StreamGobbler(InputStream is, String type, OutputStream redirect) {
this.is = is;
this.type = type;
this.os = redirect;
}

public void run() {
try {
PrintWriter pw = null;
if (os != null)
pw = new PrintWriter(os);

InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (pw != null)
pw.println(line);
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
[/code]
[b]问题补充:[/b]
我之前也用 java-unrar-0.2 这种方式。但是没有弄好。

这个例子给我灵感了,谢谢。

public class Test {

/**
 * 解压缩rar文件
 * 
 * @param rarFileName
 * @param extPlace
 */
public static boolean decompressionRarFiles(String rarFileName, String extPlace) {
    boolean flag = false;
    Archive archive = null;
    File out = null;
    File file = null;
    File dir = null;
    FileOutputStream os = null;
    FileHeader fh = null;
    String path, dirPath = "";
    try {
        file = new File(rarFileName);
        archive = new Archive(file);
    } catch (RarException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        if (file != null) {
            file = null;
        }
    }
    if (archive != null) {
        try {
            fh = archive.nextFileHeader();
            while (fh != null) {
                path = (extPlace + fh.getFileNameString().trim()).replaceAll("\\\\", "/");
                int end = path.lastIndexOf("/");
                if (end != -1) {
                    dirPath = path.substring(0, end);
                }
                try {
                    dir = new File(dirPath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                } catch (RuntimeException e1) {
                    e1.printStackTrace();
                } finally {
                    if (dir != null) {
                        dir = null;
                    }
                }
                if (fh.isDirectory()) {
                    fh = archive.nextFileHeader();
                    continue;
                }
                out = new File(extPlace + fh.getFileNameString().trim());
                try {
                    os = new FileOutputStream(out);
                    archive.extractFile(fh, os);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (RarException e) {
                    e.printStackTrace();
                } finally {
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (out != null) {
                        out = null;
                    }
                }
                fh = archive.nextFileHeader();
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            fh = null;
            if (archive != null) {
                try {
                    archive.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        flag = true;
    }
    return flag;
}

public static void main(String[] args) {
    String absPath="D:\\apache-tomcat-6.0.20\\webapps\\upload\\test\\系统管理.rar"; //文件绝对目录 
    String toPath ="D:\\apache-tomcat-6.0.20\\webapps\\upload\\test\\"; //文件目录
    boolean flag = new Test().decompressionRarFiles(absPath, toPath);
    System.out.println("flag ---"+flag);

}

}

上边是实现方式可以看一下。

  • 写回答

2条回答 默认 最新

  • zhoujuan520 2009-06-17 09:55
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向