2017-08-19 46 views
0

我有一个zip文件(在jar文件中),我想读取init。 我知道我可以使用getResourceAsStream(...)轻松读取txt文件,避免错误“URI不分层”。 但现在肯定我会如何做zip文件。如何阅读jar文件中的zip文件

以下是我的代码,但是当我将代码导出到runnable jar并运行它时,它会引发“URI not hierachical error”错误。

URL fileLocation = ChemicalSynonyms.class.getClassLoader().getResource("sciome/workbench/resources/chemicalSynonym/" + strFileName); 
     File file = new File(fileLocation.toURI()); 

     // it is a zip file 
     ZipFile zipFile = new ZipFile(file); 
     Enumeration<? extends ZipEntry> entries = zipFile.entries(); 
     ZipEntry entry = entries.nextElement(); 
     InputStream is = zipFile.getInputStream(entry); 
     BufferedReader buf = new BufferedReader(new InputStreamReader(is)); 
     String lineJustFetched = null; 
     String[] wordsArray; 

     // read each line 
     lineJustFetched = buf.readLine(); 
+0

哪条线会抛出错误?第一行是 – ssc327

+0

。我知道txt文件,它应该是getresourceasstream而不是getresource,但不知道我将如何处理zip文件 – user1631306

+0

不能加载资源文件流并将其附加到ZipFile类?或者可能在文件系统中创建临时文件,然后加载。 –

回答

0

它可以通过使用扫描仪来完成。例如:

 InputStream is = MainClass.class.getClassLoader().getResourceAsStream(file location with zip file name); 
     ZipInputStream zis = new ZipInputStream(is); 
     ZipEntry ze = zis.getNextEntry(); 
     Scanner sc = new Scanner(zis); 

     String[] wordsArray; 
     while (sc.hasNextLine()) 
     { 
      .... 
     }