我在 Eclipse 中使用 MyBatis 时发现了奇怪的行为。
我很难用 MyBatis 找到我的 xml,所以我尝试使用绝对路径(只是为了测试目的),但它仍然抛出错误:
为了确保该文件存在,我添加了在将其用作资源之前检查文件是否存在,因此我确定该文件存在:
String resource = "e:/prace/workspace/SpringBatis/src/main/java/com/mkyong/MyBatis/xml/batisConfig.xml";// path of the mybatis configuration file.
File file = new File(resource);
System.out.println(file.exists());
Reader reader = Resources.getResourceAsReader(resource);// read the mybatis confiuguration xml file
有这样的输出:
true
java.io.IOException: Could not find resource e:/prace/workspace/SpringBatis/src/main/java/com/mkyong/MyBatis/xml/batisConfig.xml
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:89)
有什么想法吗?
最佳答案
你有两个场景
使用 java io 读取文件。因为你已经给出了绝对路径。如果文件存在,它将始终读取该文件。
String resource = "e:/prace/workspace/SpringBatis/src/main/java/com/mkyong/MyBatis/xml/batisConfig.xml";// path of the mybatis configuration file. File file = new File(resource); System.out.println(file.exists()); Reader reader = new FileReader(resource);
您尝试读取配置文件的场景是使用资源(我相信这是您的主要目标)。资源类总是尝试从类路径读取文件。这是来自 Resources.java 类的 java 注释作为证明。
/* * Gets a URL as a Reader * * @param urlString - the URL to get * @return A Reader with the data from the URL * @throws java.io.IOException If the resource cannot be found or read */ public static Reader getUrlAsReader(String urlString) throws IOException {}
现在如何解决这个问题
从文件夹结构我假设你正在使用 Maven。因此,默认情况下,您的类路径将是 SpringBatis/src/main/java
或 SpringBatis/src/main/resources
因此,您可以将资源路径提供为 com/mkyong/MyBatis/xml/batisConfig.xml
,在你的例子中,当前资源路径是 e:/prace/workspace/SpringBatis/src/main/java/e:/prace/workspace/SpringBatis/src/main/java/com/mkyong/MyBatis/xml/batisConfig.xml
因此您的代码应该是这样的。
String resource = "com/mkyong/MyBatis/xml/batisConfig.xml";// path of the mybatis configuration file.
// File file = new File(resource);
System.out.println(file.exists());
// Reader reader = new FileReader(resource);
如果您使用的是 eclipse,您可以按如下方式验证类路径。 在项目-> 项目属性-> java 构建路径-> 源选项卡上。 您应该找到所有相关的类路径。例如,对于您的项目 SpringBatis,您会发现 SpringBatis/main/java 包含文件、排除文件、输出目录等。
注意
由于你已经将 batisConfig.xml 放在了 src/main/java 下。默认情况下,maven 配置为仅包含 */*.java
文件(仅 java 文件),如果需要包含您需要相应配置的所有文件。但我建议将 xml 文件移动到 src/main/resources 目录(这又是一个类路径)
关于java - MyBatis 加载 XML : java. io.IOException: Could not find resource (eclipse),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22176966/