你有2个场景
>使用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类总是尝试从类路径中读取文件.这是来自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目录(这也是一个类路径)