有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用getCodeBase()在Java小程序中查找和加载文件?

第一次在这里发帖,会尽量简洁。这是一个典型的“小程序内无法访问文件”问题,但我遇到了一个特别的困难

我正试图重写这个文件:

A JavaSound test for libpd

将libpd(https://github.com/libpd/libpd)补丁加载到模板小程序中,该补丁由PureData(PureData.info)生成。。。这已经在非小程序Java程序(见上文)中的正常主函数中起作用,其中主函数使用以下方法查找修补程序:

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“handle”(出于传统原因,dollarZero)来识别每个补丁,以便传递int handle来打开和关闭补丁文件

所以现在。我正试图将同一个文件加载到一个小程序中,因为我相信它“在客户端”运行,并且不知道我在说什么路径,所以我读了java。网并尝试构建以下内容的变体:

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

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

受applet的init()和start()函数中的previous questions启发,将原始main转换为本地静态方法sound()

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


共 (1) 个答案

  1. # 1 楼答案

    libpd只是纯数据之上的一个薄包装器,纯数据不知道Java中的url或输入流。openPatch方法只将补丁名和目录发送给Pd,然后Pd将尝试打开相应的文件。所以,小程序已经过时了,除非你愿意修改安全策略

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