java - 未从 `resources` 目录中检测到文件

标签 java

我正在尝试从项目中的资源导入文件。我指定 SOLVER_CONFIGresources 的根部获取 solver.xml

package in.co.technovia.sudoku;

import java.util.ArrayList;
....
public class App{
    private static final String SOLVER_CONFIG = "/solver.xml";
    public static void main(String[] args){
    SudokuGenerator sg = new SudokuGenerator();
    ....
    }

    private static Solver createSolver(){

    XmlSolverConfigurer configurer = new XmlSolverConfigurer();
        configurer.configure(SOLVER_CONFIG);
        return configurer.buildSolver();
    }
}

它应该从resources的根部获取solver.xml。它在 this case 中有效,但反复无常的 Java 诸神对我的项目另有规定:

jesvin@Jesvin-Technovia:~/dev/drools/sudoku$ java in.co.technovia.sudoku.AppException in thread "main" java.lang.IllegalArgumentException: The solver configuration (/solver.xml) does not exist.
    at org.drools.planner.config.XmlSolverConfigurer.configure(XmlSolverConfigurer.java:79)
    at in.co.technovia.sudoku.App.createSolver(App.java:67)
    at in.co.technovia.sudoku.App.main(App.java:43)

问题:为什么 Java 没有检测到资源中的文件?

<小时/>

我包含了 src/main/java/in/co/technovia/sudoku/ 应用程序和 src/main/resources/ 目录以及当前的内容类路径。

jesvin@Jesvin-Technovia:~/dev/drools/sudoku$ ls src/main/resources/
score.drl  score.drl~  solver.xml  solver.xml~

jesvin@Jesvin-Technovia:~/dev/drools/sudoku$ ls src/main/java/in/co/technovia/sudoku/
App.class  App.java~  helloworld.class  helloworld.java~
App.java   domain     helloworld.java   solution

jesvin@Jesvin-Technovia:~/dev/drools/sudoku$ export | grep CLASSPATHdeclare -x   
CLASSPATH=".:/home/jesvin/dev/drools/sudoku/binaries/*:/home/jesvin/dev/drools/sudoku/src/main/java"
<小时/>

解决方案: 正如 khmarbaise 在他的回答中所说,该目录用于 Maven 构建。因此要包含该目录,请参阅“https://stackoverflow.com/a/9045680/604511”。

最佳答案

您似乎错误地理解了 src/main/resources 文件夹在 Maven 构建中的用途。文件夹 src/main/resources 在构建过程中被复制到 target/classes 文件夹中,该文件夹代表您可以在 java 应用程序中使用的资源:

this.getResourceAsStream("/solver.xml")...

它返回一个InputStream而不是File对象。以下方法可用于从中获取文件,但此方法不适用于类路径中的 JAR,只能适用于文件和目录。

URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());

关于java - 未从 `resources` 目录中检测到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9044898/

相关文章:

java - Jlist 的换行/字符串生成器的下一行

java - 如何使用反射检查对象的通用类型?

java - Android ListView 无法滚动更多,自定义适配器不好?

java - eclipse 错误代码新手请

java - Hibernate + Spring - 找不到 xml 映射

java - 在 Google App Engine 上从 Java 7 迁移到 Java 8 时出现内存错误/500 错误

java - Maven并行测试输出

java - Java中的代码结构是什么?

java - Spark-jobserver 0.7.0 的 Maven 存储库

Java JFrame gui - 为什么按钮不显示?