How to read a file from jar in Java?

后端 未结 5 1348
我寻月下人不归
我寻月下人不归 2020-11-22 05:45

I want to read an XML file that is located inside one of the jars included in my class path. How can I read any file which is included in the jar?<

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 06:44

    A JAR is basically a ZIP file so treat it as such. Below contains an example on how to extract one file from a WAR file (also treat it as a ZIP file) and outputs the string contents. For binary you'll need to modify the extraction process, but there are plenty of examples out there for that.

    public static void main(String args[]) {
        String relativeFilePath = "style/someCSSFile.css";
        String zipFilePath = "/someDirectory/someWarFile.war";
        String contents = readZipFile(zipFilePath,relativeFilePath);
        System.out.println(contents);
    }
    
    public static String readZipFile(String zipFilePath, String relativeFilePath) {
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            Enumeration e = zipFile.entries();
    
            while (e.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                // if the entry is not directory and matches relative file then extract it
                if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
                    BufferedInputStream bis = new BufferedInputStream(
                            zipFile.getInputStream(entry));
                    // Read the file
                        // With Apache Commons I/O
                     String fileContentsStr = IOUtils.toString(bis, "UTF-8");
    
                        // With Guava
                    //String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
                    // close the input stream.
                    bis.close();
                    return fileContentsStr;
                } else {
                    continue;
                }
            }
        } catch (IOException e) {
            logger.error("IOError :" + e);
            e.printStackTrace();
        }
        return null;
    }
    

    In this example I'm using Apache Commons I/O and if you are using Maven here is the dependency:

    
        commons-io
        commons-io
        2.4
    
    

提交回复
热议问题