【发布时间】:2019-04-22 10:22:20
【问题描述】:
我以前用这个方法读取我的maven的resources/目录下的文本文件,这样就可以使用相对路径了:
public static BufferedReader fileReaderAsResource(String filePath) throws IOException {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
if (is == null) {
throw new FileNotFoundException(" Not found: " + filePath);
}
return new BufferedReader(new InputStreamReader(is, DEFAULT_ENCODING));
}
现在我需要读取 zip 文件,因为它的大小,我仍然想在我的“资源”目录中使用文件的相对路径。有没有办法做到这一点?
我有这种读取zip文件的方法,但它只能通过绝对路径读取文件:
public static BufferedReader fileZipReader(String fileName) throws IOException, URISyntaxException {
URL zipUrl = IOUtils.class.getClassLoader().getResource(fileName);
File zipFile = new File(zipUrl.toURI());
ZipFile zip = new ZipFile(zipFile);
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry zipEntry = (ZipEntry) e.nextElement();
if (!zipEntry.isDirectory()) {
return new BufferedReader(new InputStreamReader(zip.getInputStream(zipEntry)));
}
}
throw new FileNotFoundException("File not found: " + fileName);
}
如何通过我的标准 maven 资源/目录的相对路径读取 zip 文件?
【问题讨论】:
-
File zipFile = new File(zipUrl.toURI());File不能表示指向 Zip 条目的 URL。如果代码确实需要一个文件,那么首先需要将信息提取到一个文件中。
标签: java maven zip inputstream