【问题标题】:Java - Cannot get MIDI file as resourceJava - 无法获取 MIDI 文件作为资源
【发布时间】:2014-05-04 11:19:23
【问题描述】:

我最初在项目目录中有我的 .mid 文件,我得到它是这样的:

 File file = new File("hmr.mid");

一切正常,然后我尝试将其导出到 可运行的 .jar,因为稍后我尝试访问该文件时遇到了 NullPointerException

我已经读到我应该将资源添加到包中,所以我这样做了:

http://kepfeltoltes.hu/140326/115027543proj_www.kepfeltoltes.hu_.png

从那以后,我进行了大量的谷歌搜索、SOF 搜索,查看了大量示例(我认为大多数人都弄错了,例如使用绝对路径),阅读如下文章:

http://www.thinkplexx.com/learn/howto/java/system/java-resource-loading-explained-absolute-and-relative-names-difference-between-classloader-and-class-resource-loading

但没有任何效果。我只是在导出到 .jar 时收到 NullPointerException,但即使我只是运行它。

这是我的资源加载器,其中包含我的一些尝试。它适用于图像。

import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.InputStream;
import java.net.URL;




public class ResourceLoader {

static ResourceLoader rl = new ResourceLoader();

public static Image getImage(String filename)
{
    return Toolkit.getDefaultToolkit().getImage(rl.getClass().getResource(filename));
}

public static File getFile(String filename)
{
    //InputStream is = rl.getClass().getResourceAsStream("hmr.mid");
    //URL url = Thread.currentThread().getContextClassLoader().getResource("hmr.mid");
    //File file = new File(url.toString());
    //url = File.class.getClassLoader().getResource("/Users/peti/Documents/workspace/java_workspace/BluesBox_v0_21/200_Stlye/resources/hmr.mid");

    //File file = new File(url.getFile());
    //File file = new File("/Users/peti/Documents/workspace/java_workspace/BluesBox_v0_21/200_Stlye/resources/hmr.mid");
    //File file = new File("src/200_Stlye/resources/hmr.mid");
    File file = new File("hmr.mid");

    return file;
}

}

【问题讨论】:

    标签: java file resources classloader getresource


    【解决方案1】:

    使用 getClass().getResource() 时应使用资源的相对路径

    例如“/hmr.mid”

    在这种情况下,请确保您填写的是类路径。

    【讨论】:

    • 另外,它不是一个文件。事实并非如此。您无法将其作为文件获取,因为它不是文件,而文件是文件。
    • 你好尼古拉。根据文章,您的解决方案是使用绝对路径。文章错了吗?
    • 它说:“资源名称可以是:绝对如“/path/resource.xml”;相对如“path/resource.xml”;“
    • 你好,Immibis。你能提供更多细节吗?我无法理解你的意思。
    • 你给的例子是absolute path我在官方文档查过:docs.oracle.com/javase/tutorial/essential/io/path.html
    猜你喜欢
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    相关资源
    最近更新 更多