使用maven构建的可执行JAR在从静态方法

时间:2018-03-24 15:45:44

标签: java maven intellij-idea

所以我有一个小资源加载器用于我需要的东西。 jar打包资源,但是当我构建maven项目,并且所有依赖项工作和资源文件夹被标记为资源时,我的图像和脚本将不会加载。

以下是我正在使用的代码:

...

public class ResourceLoader
{
    public static ImageIcon getImageIconResource(String fileName) {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        File file = new File(classLoader.getResource("img/" + fileName).getFile());
        return new ImageIcon(file.getPath());
    }

    public static File getScriptResource(String fileName) {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        return new File(classLoader.getResource("scripts/" + fileName).getFile());
    }
}

1 个答案:

答案 0 :(得分:2)

问题不在于maven本身。当你打电话

File.getPath

在来自资源的文件上,它指向一个文件,实际上是应用程序存档中的 。对于大多数应用程序,这会产生问题,因为在不提取存档的情况下无法读取文件。要正确使用资源文件,您必须使用File,或者您可以调用

ClassLoader.getResourcesAsStream

要添加ImageIcon

public static ImageIcon getImageIconResource(String fileName) {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    InputStream is = classLoader.getResourceAsStream("img/" + fileName);
    Image image = ImageIO.read(is);
    return new ImageIcon(image);
}

至于你的getScriptResource方法,geting文件对象应该可行。但这取决于你以后如何使用它。我认为无论如何你都需要阅读它,我建议也使用输入流。

public static InpoutStream getScriptResource(String fileName) {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    InputStream is = classLoader.getResourceAsStream("scripts/" + fileName);    
    return is;
}

然后,您可以使用许多适合您需要的选项来阅读InputStream。例如,您可以查看Apache Commons' IoUtils或使用ReaderApi

处理它

修改

因为您已经阐明了如何使用您的文件,所以我可以看到您的脚本存在问题。您正在启动应用程序之外的另一个进程。在python3的第一个CLI参数中,您将提供该文件的路径。正如我之前写的 - 这是问题所在,因为python3无法读取.jar文件中的文件。首先,我会质疑你的架构。你真的需要在.jar里面写脚本吗?

无论如何,一种可能的解决方法可能是将脚本文件的内容存储在temporaryFile中。

File tempFile = File.createTempFile("prefix-", "-suffix");
// e.g.: File tempFile = File.createTempFile("MyAppName-", ".tmp");
tempFile.deleteOnExit();
//get your script and prepare OutputStream to tempFile
// Try with resources, because you want to close your streams
try (InputStream is = ResourceLoader.getScriptResource(scriptName);
     FileOutputStream out = new FileOutputStream(tempFile)) {
    //NOTE: You can use any method to copy InputStream to OutputStream.
    //Here I have used Apache IO Utils
    IOUtils.copy(is, out);
}
boolean success = executePythonScriptWithArgs(tempFile, args);