无法在Tomcat 7.0.22上将Jar文件的内容写入本地Servlet

时间:2011-10-09 18:26:16

标签: java tomcat servlets jar fileoutputstream

下午好,

我试图以编程方式提取jar文件的内容,并找到一个代码片段here,它允许我在不使用servlet的情况下在本地机器上提取jar文件的内容。

现在我知道代码工作了,我试图在本地servlet环境中使用它,特别是Tomcat 7.0.22。到目前为止,我有下面的代码,但无法输出jar的内容。我相信我没有正确处理输出流,这就是为什么没有任何东西保存到我本地Tomcat服务器的本地目录。

是否有人能够指出我正确的方向或提供一些如何更正代码的建议,以便将读取的内容输出到文件中?

import java.io.*;
import java.util.*;
import javax.servlet.*;


@SuppressWarnings("serial")
public class JarExtractor extends HttpServlet {
  @SuppressWarnings("rawtypes")
  protected void doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {
    try {

        String path = getServletContext().getRealPath("test.jar");
        JarFile jar = new JarFile(path);
        Enumeration jarEnum = jar.entries();

        while (jarEnum.hasMoreElements()) {
            JarEntry file = (JarEntry) jarEnum.nextElement();
            File f = new File(file.getName());
            if (file.isDirectory()) {       // if its a directory, create it
                f.mkdir();
                continue;
            }
            InputStream in = jar.getInputStream(file); // get the input stream
            OutputStream output = new FileOutputStream(f);
            while (in.available() > 0) {  // write contents of 'is' to 'fos'
                output.write(in.read());
            }
            output.close();
            in.close();
        }
    }
    catch(Exception ex) 
    {
        //------
    }   
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws   ServletException, IOException {
  try 
      {
      doPost(request,response);
  } 
      catch (ServletException e) 
      {
    // 
  } 
      catch (IOException e) 
      {
    //
  }
}

}

非常感谢任何人能够提供的任何帮助。

享受你的周末!

1 个答案:

答案 0 :(得分:0)

输出文件也需要基于真实路径(或其他已知位置),否则您可能只是根据jar组件的名称在servlet上下文之外写入一个位置。

相关问题