如何在运行时将文件添加到Java类路径?
我正在运行时创建一个功能文件,并尝试在创建后访问该文件。我遵循了所有给出的方法 [编辑]添加示例代码如何在运行时将文件添加到Java类路径?,java,cucumber,Java,Cucumber,我正在运行时创建一个功能文件,并尝试在创建后访问该文件。我遵循了所有给出的方法 [编辑]添加示例代码 public static void createFeatureFile(String featurePath) throws IOException{ FileWriter writer = new FileWriter(featurePath); writer.append("Feature: Test "); writer.append("\n");
public static void createFeatureFile(String featurePath) throws IOException{
FileWriter writer = new FileWriter(featurePath);
writer.append("Feature: Test ");
writer.append("\n");
writer.append("\n");
writer.append("@test");
writer.append("\n");
writer.append("Scenario : add fruits");
writer.append("\n");
writer.append("Given I have 1 apple and 1 orange");
writer.append("\n");
writer.append("Then I add both"");
writer.append("\n");
writer.flush();
writer.close();
File file =new File(featurePath);
addFileAtRunTime(file);
}
private static void addFileAtRunTime(File file) throws Exception {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}
试试这件衣服的尺寸
private static void addFileAtRunTime(File file) throws Exception {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}
这将编辑系统类加载器以包含给定文件。您应该查看自定义类加载器。
private static void addFileAtRunTime(File file) throws Exception {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}