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");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句