简体   繁体   中英

get csv file from jar

I have the following line of code:

InputStreamReader isr = new InputStreamReader(MethodHandles.lookup().lookupClass().getResourceAsStream(csvFile));

could someone explain to a newbe:

MethodHandles.lookup()
lookupClass()
getResourceasStream()

the code works and accesses a csv file located in a jar. I just don't understand what each of the methods is doing

I was able to simplify the line to:

InputStreamReader isr = new InputStreamReader (SQLUtilPROD.class.getResourceAsStream (csvFile));

but still confused. What does SQLUtilProd.class do? and how does getResourceAsStream know to get the file from the jar? What happens if you have multiple jars?

Not sure but I think we use SQLUtil.class to get the class object which in turns gives us access to classLoader which getResourceAsStream uses to locate the file.

If that's true where does classLoader define the path to include the jar?

What does SQLUtilProd.class do?

The data for each object contains a reference to an object of class java.lang.Class, and this is returned by the method getClass. There is also one java.lang.Class object describing java.lang.Class. Please read more in this link.

how does getResourceAsStream know to get the file from the jar?

getResourceAsStream will find a resource on the classpath with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. Please visit this link.

What happens if you have multiple jars?

You can get all resources with a helper function like this:

public static List<InputStream> loadResources(
        final String name, final ClassLoader classLoader) throws IOException {
    final List<InputStream> list = new ArrayList<InputStream>();
    final Enumeration<URL> systemResources = 
            (classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader)
            .getResources(name);
    while (systemResources.hasMoreElements()) {
        list.add(systemResources.nextElement().openStream());
    }
    return list;
}

I'm sure that reading this link will help you.

where does classLoader define the path to include the jar?

The system ClassLoader provides access to information in the CLASSPATH . A CLASSPATH may contain directories and JAR files. So you have access to all resources of your project and jar files which they are in the classpath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM