繁体   English   中英

从jar文件获取资源

[英]Get resources from a jar file

我希望我的jar文件可以从自身访问某些文件。 我知道如何为BufferedImage执行此操作,但这不适用于其他文件。 我只想从罐子里取出一些拉​​链。 我在Eclipse中制作了一个课程文件夹,将拉链放入其中并使用了

    public File getResFile(String name){

    return new File(getClass().getResource(name).getFile());


}

获取File实例并将其解压缩。 它在日食中工作正常,但是一旦我将其导出到罐子中,它就会说

Exception in thread "main" java.io.FileNotFoundException: file:\C:\Users\DeLL\Desktop\BoxcraftClient\ClientInstaller.jar!\client.bxc (The filename, directory name, or volume label syntax is incorrect)
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:220)
    at java.util.zip.ZipFile.<init>(ZipFile.java:150)
    at java.util.zip.ZipFile.<init>(ZipFile.java:164)
    at Launcher.install(Launcher.java:43)
    at Launcher.main(Launcher.java:33)

我正在努力解决这个问题,大概需要6个小时,却找不到解决方案。 请帮忙!

还有一个原因是getResource()返回一个URL ,而不是一个File ,因为该资源可能不是一个文件,因为你的代码被打包在JAR文件中,它不是一个文件,而是一个zip条目。

读取资源内容的唯一安全方法是作为InputStream ,方法是调用getResourceAsStream()或对返回的URL调用openStream()

使用以下方法之一,从类Class - getResource(java.lang.String) -getResourceAsStream(java.lang.String)

    this.getClass().getResource(name);
    this.getClass().getResourceAsStream(name);

警告:默认情况下,它从包中的this.class位置加载文件。 因此,如果从类org.organisation.project.App使用它,则该文件需要位于org/organisation/project目录的jar中。 如果该文件是位于根,或一些其他目录,罐子内,使用/ ,在从文件名的。 /data/names.json一样。

首先使用java System.out.println("classpath is: " + System.getProperty("java.class.path"));检查您的类路径System.out.println("classpath is: " + System.getProperty("java.class.path")); 查看类路径是否包含您的jar文件。

然后使用getclass()。classloader.getResourceAsStream(name)。 查看返回的URL是否正确。 在URL上调用方法isFile()以检查URL是否实际上是一个文件。 然后调用getFile()方法。

使用Spring的PathMatchingResourcePatternResolver ;

从IDE或从文件系统启动软件包都将达到目的:

public List<String> getAllClassesInRunningJar() throws Exception {
    try {
        List<String> list = new ArrayList<String>();

        // Get all the classes inside the package com.my.package:
        // This will do the work for both launching the package from an IDE or from the file system:  
        String scannedPackage = "com.my.package.*";

        // This is spring - org.springframework.core; use these imports:
        //  import org.springframework.core.io.Resource;
        //  import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
        PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
        Resource[] resources = scanner.getResources(scannedPackage.replace(".", "/"));

        for (Resource resource : resources)
            list.add(resource.getURI().toString());
        return list ;
    } catch (Exception e) {
        throw new Exception("Failed to get the classes: " + e.getMessage(), e);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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