gpt4 book ai didi

java - 在 "ZipFile zipfile = new ZipFile("X 中设置路径 X");"

转载 作者:行者123 更新时间:2023-11-29 06:19:13 28 4
gpt4 key购买 nike

我在 ZipFile zipfile = new ZipFile("X"); 中设置 zip 文件 X 的路径时遇到问题。

我不想对路径进行硬编码,使其成为 ZipFile zipfile = new ZipFile("C:/docs/data.zip");
我想做类似的事情:

ZipFile zipfile = new ZipFile(getServletContext().getResourceAsStream("/WEB-INF/" + request.getAttribute("myFile").toString());

其中zip文件的路径由用户的选择决定。但是,这会出错,因为这仅适用于 InputStream。

之前,我已经检索了 multipart/form 数据并获得了 zip 文件的真实路径:

String path = getServletContext().getRealPath("/WEB-INF");
UploadBean bean = new UploadBean();
bean.setFolderstore(path);
MultipartFormDataRequest multiPartRequest = new MultipartFormDataRequest(request);
bean.store(multiPartRequest); //store in WEB-INF

// get real path / name of zip file which is store in the WEB-INF
Hashtable files = multiPartRequest.getFiles();
UploadFile upFile = (UploadFile) files.get("file");
if (upFile != null) request.setAttribute("myFile", upFile.getFileName());

有什么解决办法吗?

最佳答案

您可以通过两种方式将网页内容相对路径转换为绝对磁盘文件系统路径:

  1. 只需使用 ServletContext#getRealPath()正如您之前所做的那样。

    ZipFile zipfile = new ZipFile(getServletContext().getRealPath("/WEB-INF/" + request.getAttribute("myFile").toString()));
  2. 使用 ServletContext#getResource()反而。它返回一个 URL。对其调用 getPath()

    ZipFile zipfile = new ZipFile(getServletContext().getResource("/WEB-INF/" + request.getAttribute("myFile").toString()).getPath());

方式#1 是首选。

关于java - 在 "ZipFile zipfile = new ZipFile("X 中设置路径 X");",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3824443/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com