Java 在tomcat web应用程序的类路径中动态添加属性文件
我正在尝试向类路径动态添加一个属性文件,如下所示Java 在tomcat web应用程序的类路径中动态添加属性文件,java,jakarta-ee,classpath,Java,Jakarta Ee,Classpath,我正在尝试向类路径动态添加一个属性文件,如下所示 try { File fileToAdd = new File(FILE_PATH); URL u = fileToAdd.toURL(); ClassLoader sysLoader = ClassLoader.getSystemClassLoader(); if (sysLoader instanceof URLClassLoader) { sysLoader = (URLClassLoader) sy
try {
File fileToAdd = new File(FILE_PATH);
URL u = fileToAdd.toURL();
ClassLoader sysLoader = ClassLoader.getSystemClassLoader();
if (sysLoader instanceof URLClassLoader) {
sysLoader = (URLClassLoader) sysLoader;
Class<URLClassLoader> sysLoaderClass = URLClassLoader.class;
// use reflection to invoke the private addURL method
Method method = sysLoaderClass.getDeclaredMethod("addURL",
new Class[] { URL.class });
method.setAccessible(true);
method.invoke(sysLoader, new Object[] { u });
}
} catch (Exception e) {
logger.error(e.getMessage());
}
我在这个列表中看不到我的文件。我在这里遗漏了什么吗?也许可以尝试一下这段代码,但要更改java.library.path,或者保持原样,如果您可以改用library路径的话
/**
* Allows you to add a path to the library path during runtime
* @param dllLocation The path you would like to add
* @return True if the operation completed successfully, false otherwise
*/
public boolean addDllLocationToPath(final String dllLocation)
{
//our return value
boolean retVal = false;
try
{
System.setProperty("java.library.path", System.getProperty("java.library.path") + ";" + dllLocation);
//get the sys path field
Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);
retVal = true;
}
catch (Exception e)
{
System.err.println("Could not modify path");
}
return retVal;
}
无法添加属性文件的URL,必须添加属性文件所在目录的URL。如:
method.invoke(sysLoader,fileToAdd.getParent().tour())代码>
然后可以使用ClassLoader.getResourceAsStream(“my.properties”)
类加载器将在新添加的目录中搜索该文件
从
此类加载器用于从引用JAR文件和目录的URL的搜索路径加载类和资源。任何以“/”结尾的URL都被假定为引用目录。否则,该URL被假定为引用将根据需要打开的JAR文件
/**
* Allows you to add a path to the library path during runtime
* @param dllLocation The path you would like to add
* @return True if the operation completed successfully, false otherwise
*/
public boolean addDllLocationToPath(final String dllLocation)
{
//our return value
boolean retVal = false;
try
{
System.setProperty("java.library.path", System.getProperty("java.library.path") + ";" + dllLocation);
//get the sys path field
Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);
retVal = true;
}
catch (Exception e)
{
System.err.println("Could not modify path");
}
return retVal;
}