JAVA DLL 的库路径 INPUT/OUTPUT

JAVA library path INPUT/OUTPUT for DLL

我有 java 调用 C 类 的 Web 应用程序编译成 .DLL。当前 DLL 需要 INPUT 文件并将其用作字典。我的 Web 应用程序部署在 Tomcat - 所以为了使一切正常工作,我必须将我的字典输入文件放在 C:\apache-tomcat-7.0.14\bin 目录下,否则 DLL 无法找到它。

我认为这不是我输入文件的好位置。您能否建议我如何为我的输入文件配置不同的位置?

感谢您的帮助!

如果您修改本机 C 代码以接受文件路径,这就不是问题了,因为您的 Java 代码可以指定文件的位置。

在你的 Java class:

public class Test {
  public native void toSomethingWithDictionary(String dictionaryFile);
}

在你的 C 代码中:

#include <sys/errno.h>
#include <string.h>
#include "test.h"

#define ERROR_MESSAGE_LENGTH 255

JNIEXPORT void JNICALL Java_Test_toSomethingWithDictionary
  (JNIEnv *env, jobject instance, jstring dictionaryFile)
{
    FILE *dict;
    const char *dict_path;

    dict_path = (*env)->GetStringUTFChars(env, dictionaryFile, 0);

    if(NULL == (dict = fopen(dict_path, "r"))) {
      /* Failed to open the file. Why? */
      char error_msg[ERROR_MESSAGE_LENGTH];

      strerror_r(errno, error_msg, ERROR_MESSAGE_LENGTH);

      strncat(error_msg, ": ", ERROR_MESSAGE_LENGTH - strlen(error_msg) - 1);

      strncat(error_msg, dict_path, ERROR_MESSAGE_LENGTH - strlen(error_msg) - 1);

      jclass ioe = (*env)->FindClass(env, "java/io/IOException");
      if(NULL == ioe) {
        goto cleanup;
      }
      (*env)->ThrowNew(env, ioe, error_msg);
      goto cleanup;
    }

    /* do whatever you want with your dictionary file */

    fclose(dict);

    cleanup:
    (*env)->ReleaseStringUTFChars(env, dictionaryFile, dict_path);
}

如果您希望 Test class 有一个更复杂的接口,您可以使用 public void setDictionaryPath(String dictionaryPath) 方法,然后让您的本机代码使用它来定位文件。

现在,当您准备好在 Web 应用程序中使用 class 时,只需执行以下操作:

Test test = new Test();
test.doSomethingWithDictionary("/usr/share/dict/words");

或者,如果您想将文件动态地放到磁盘上:

ServletContext app = getServletContext();
Test test = new Test();
test.doSomethingWithDictionary(app.getRealPath("/META-INF/dict"));
/* NOTE: getRealPath is a bad API call to use. Find a better way. */