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文件,如何返回BufferedReader?由于“fileName”是我的“resources”目录下的相对路径,以下内容不起作用:
public static BufferedReader fileZipReader(String fileName) throws IOException {
ZipFile zip = new ZipFile(fileName);
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);
}
如何更改“fileZipReader”以使其正常工作?
最佳答案
创建一个 URL 对象,提供 zip 文件的相对路径。
public class IOUtil {
public 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);
}
public static void main(String[] args) throws Exception {
IOUtil util = new IOUtil();
BufferedReader br = util.fileZipReader("dia/test.txt.zip");
}
}
关于java - 如何从资源目录中的 zip 文件获取 BufferedReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49664126/