`
aben328
  • 浏览: 1451639 次
  • 性别: Icon_minigender_1
  • 来自: 广东
社区版块
存档分类

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

    博客分类:
  • java
阅读更多

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

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

文件1:UnrarServlet
代码
Java代码 复制代码
  1. package com.jh.upload.servlet;   
  2.   
  3. import java.io.BufferedInputStream;   
  4. import java.io.BufferedOutputStream;   
  5. import java.io.BufferedReader;   
  6. import java.io.File;   
  7. import java.io.FileOutputStream;   
  8. import java.io.IOException;   
  9. import java.io.InputStream;   
  10. import java.io.InputStreamReader;   
  11. import java.io.PrintWriter;   
  12.   
  13. import javax.servlet.ServletException;   
  14. import javax.servlet.http.HttpServlet;   
  15. import javax.servlet.http.HttpServletRequest;   
  16. import javax.servlet.http.HttpServletResponse;   
  17.   
  18. import org.apache.tools.zip.ZipEntry;   
  19. import org.apache.tools.zip.ZipFile;   
  20.   
  21.   
  22. @SuppressWarnings("serial")   
  23. public class UnrarServlet extends HttpServlet {   
  24.     private static String unrarCmd = "C:\\Program Files\\WinRAR\\unrar x";   
  25.   
  26.     public void doGet(HttpServletRequest request, HttpServletResponse response)   
  27.             throws ServletException, IOException {   
  28.         doPost(request, response);   
  29.     }   
  30.   
  31.     @SuppressWarnings( { "static-access""deprecation" })   
  32.     public void doPost(HttpServletRequest request, HttpServletResponse response)   
  33.             throws ServletException, IOException {   
  34.         request.setCharacterEncoding("gbk");   
  35.         response.setContentType("text/html;charset=gbk");   
  36.         // 设置字符编码为UTF-8, 这样支持汉字显示   
  37.         response.setCharacterEncoding("gbk");   
  38.   
  39.         //文件名 传进来或者取过来   
  40.         String file = "系统管理.rar";   
  41.         PrintWriter out = response.getWriter();   
  42.   
  43.         String rarFileName = request.getRealPath("/test") + "\\" + file;   
  44.         String destDir = request.getRealPath("/test");   
  45.   
  46.         File f = new File(rarFileName);   
  47.         if ((!f.exists()) && (f.length() <= 0)) {   
  48.             out.println("要解压的文件不存在!<p />");   
  49.             out.println("<a href='MyJsp.jsp' >返回</a>");   
  50.             return;   
  51.         }   
  52.   
  53.         unrarCmd += " " + rarFileName + " " + destDir;   
  54.         try {   
  55.             Runtime rt = Runtime.getRuntime();   
  56.             Process p = rt.exec(unrarCmd);   
  57.          
  58.   
  59.             StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(),"ERROR");               
  60.             errorGobbler.start();   
  61.             StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(),"STDOUT");   
  62.             //  kick  off  stdout     
  63.             outGobbler.start();   
  64.             p.waitFor();   
  65.   
  66.             System.out.println("进程:--"+p.exitValue());   
  67.         } catch (Exception e) {   
  68.             System.out.println(e.getMessage());   
  69.   
  70.         }   
  71.   
  72.         //判断目录是否存在   
  73.         String fileName = file.substring(0, file.lastIndexOf("."));   
  74.   
  75.         File filePath = new File(destDir + "\\" + fileName);   
  76.   
  77.         if (filePath.isDirectory()) {   
  78.             out.println("<p />解压成功!");   
  79.         } else {   
  80.             out.println("<p />解压失败,请手工解压!");   
  81.         }   
  82.   
  83.         out.println("<p /><a href='MyJsp.jsp' >返回</a>");   
  84.         return;   
  85.   
  86.     }   
  87.        
  88. }  
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;

    }
    
}

文件2:StreamGobbler.java
Java代码 复制代码
  1. import java.io.BufferedReader;   
  2. import java.io.IOException;   
  3. import java.io.InputStream;   
  4. import java.io.InputStreamReader;   
  5. import java.io.OutputStream;   
  6. import java.io.PrintWriter;   
  7.   
  8. public class StreamGobbler extends Thread {   
  9. InputStream is;   
  10. String type;   
  11. OutputStream os;   
  12.   
  13. StreamGobbler(InputStream is, String type) {   
  14. this(is, type, null);   
  15. }   
  16.   
  17. StreamGobbler(InputStream is, String type, OutputStream redirect) {   
  18. this.is = is;   
  19. this.type = type;   
  20. this.os = redirect;   
  21. }   
  22.   
  23. public void run() {   
  24. try {   
  25. PrintWriter pw = null;   
  26. if (os != null)   
  27. pw = new PrintWriter(os);   
  28.   
  29. InputStreamReader isr = new InputStreamReader(is);   
  30. BufferedReader br = new BufferedReader(isr);   
  31. String line = null;   
  32. while ((line = br.readLine()) != null) {   
  33. if (pw != null)   
  34. pw.println(line);   
  35. System.out.println(type + ">" + line);   
  36. }   
  37. if (pw != null)   
  38. pw.flush();   
  39. catch (IOException ioe) {   
  40. ioe.printStackTrace();   
  41. }   
  42. }   
  43. }   
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();
}
}
} 

问题补充:
我之前也用 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);

}
}
--------------------------------------------------------------
上边是实现方式可以看一下。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics