java - 如何使用 getCodeBase() 在 Java Applet 中查找并加载文件?

标签 java file applet

第一次在这里发帖,尽量简洁。这是一个典型的“无法访问 Applet 中的文件”问题,但我在解决它时遇到了特别的困难。

我正在尝试重写此文件:

A JavaSound test for libpd

进入模板小程序以加载在 PureData (puredata.info) 中制作的 libpd ( https://github.com/libpd/libpd ) 补丁...这已经可以在非小程序 Java 程序中的正常 Main 函数中工作(见上文),其中 main函数使用以下命令查找补丁:

PdBase.openAudio(0, outChans, (int) sampleRate);
    int patch = PdBase.openPatch("samples/com/noisepages/nettoyeur/libpd/sample/test.pd");
    PdBase.computeAudio(true);

它尝试将路径和文件加载到 int 变量中的原因是核心函数本身通过以下方式执行此操作:

public synchronized static int openPatch(File file) throws IOException {
    if (!file.exists()) {
        throw new FileNotFoundException(file.getPath());
    }
    String name = file.getName();
    File dir = file.getParentFile();
    long ptr = openFile(name, (dir != null) ? dir.getAbsolutePath() : ".");
    if (ptr == 0) {
        throw new IOException("unable to open patch " + file.getPath());
    }
    int handle = getDollarZero(ptr);
    patches.put(handle, ptr);
    return handle;
}
public synchronized static int openPatch(String path) throws IOException {
    return openPatch(new File(path));
}

这是因为 PD 尝试通过提供 int“句柄”(由于遗留原因,dollarZero)来识别每个补丁,以便传递 int 句柄来打开和关闭补丁文件。

所以现在。我正在尝试在 Applet 中加载相同的文件,所以因为我相信它在“客户端”中运行并且不知道我在说什么路径,所以我阅读了 java.net.URL 并尝试构建的变体:

        patchURL = new URL("test.pd");
    PdBase.openPatch(patchURL.getPath().toString());

URL url = this.getClass().getResource("test.pd");

灵感来自previous questions在小程序的init()和start()函数中,将原来的main变成了本地静态方法sound()。

我得到的只是空指针。我本以为我需要的只是一个简单的 getDocumentBase(),但似乎无法使其工作。有人吗?

最佳答案

libpd 只是 Pure Data 之上的一个薄包装器,Pure Data 不了解 Java 中的 URL 或输入流。 openPatch方法只是将补丁名称和目录发送给Pd,然后Pd会尝试打开相应的文件。因此,小程序已经过时了,除非您愿意修改安全策略。

关于查找文件,简单的示例程序是 libpd Eclipse 项目的一部分。它应该在 Eclipse 中运行,并且补丁的硬编码路径是相对于 Eclipse 中的项目根目录的。如果您希望代码在不同的设置中运行,则必须相应地调整路径。

关于java - 如何使用 getCodeBase() 在 Java Applet 中查找并加载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9141755/

相关文章:

java - XML 数字签名 Java

java - 使用什么 Maven 插件可以帮助设置属性的动态值?

java - 传递到 JSONObject 类后数据丢失

java - 从android中的文本文件读取

iphone - 基于 View 的应用程序? - 请解释

java - 如何使用 pdfbox 2 设置复选框外观流的边框

performance - 加速 gz 文件上的 sed

python - 谷歌colab中的for循环列表索引超出范围

java - 在 .jar 中获取目录

java - 为什么这些图像不显示?