下午好,
我正在尝试以编程方式提取 jar 文件的内容,并在 此处找到了一个代码片段,它允许我在不使用 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)
{
//
}
}
}
非常感谢您提供的任何帮助。
周末愉快!