今天写项目在读资源的时候,在路径上遇到了问题。这一块应该说是Java基础的内容,在这里做总结和记录。
在开发JavaWeb项目时,可以把配置文件和java代码放在一起,也可以放在WEB-INF下面。Java程序是在classpath下面运行的(在IDE中是classes目录),如果放在Java代码目录下,则可以使用ClassLoader通过classpath目录很方便的找到。如果放在WEB-INF下面,则需要先找到WEB应用在操作系统上的路径,之后通过相对路径找到文件。这篇文章主要使用第一种办法。
Spring的配置文件放在WEB-INF下面,而Mybatis的配置需要放在java目录下才能找到,这或许和框架的具体实现有关。
接下来具体总结一下
一.Class.getResource()
这个方法返回URL,接受的参数是相对于当前类的路径,但也可以通过‘/’访问classpath。
二.ClassLoader.getResource()
这个方法也返回URL,接受的是classpath路径,在参数中引用'/'试图访问classpath是错误的语法。
举例:下面的三种写法效果是一样的。
com.explorers.Test.class.getResourceAsStream("abc.jpg")
com.explorers.Test.class.getResourceAsStream("/com/explorers/abc.jpg")
ClassLoader.getResourceAsStream("com/explorers/abc.jpg")
三.getPath()
这个方法参数是URL,返回基于操作系统路径,可以和上面两个方法联合调用。例如在bjtu.edu.utils.Myclass中的调用:
public void getFileLocation() {
URL a = Myclass.class.getClassLoader().getResource("edu/bjtu/fileshare/dao/config/File.xml");
String b = a.getPath();
System.out.println(a);
System.out.println(b);
}
运行结果是:
file:/D:/intellijworkspace/fileshare/target/classes/edu/bjtu/fileshare/dao/config/File.xml/D:/intellijworkspace/fileshare/target/classes/edu/bjtu/fileshare/dao/config/File.xml
之上的讨论可以用在读取配置文件的操作中。贴一段完整的代码。
package edu.bjtu.fileshare.utils;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@Component("propreader")
public class PropertiesReader {
public String getFileLocation() {
InputStream inStream = PropertiesReader.class.getClassLoader().getResourceAsStream("edu/bjtu/fileshare/utils/config/filelocation.properties");
Properties prop = new Properties();
try {
prop.load(inStream);
} catch (IOException e) {
e.printStackTrace();
}
return prop.getProperty("location");
}
public static void main(String[] args) {
PropertiesReader p = new PropertiesReader();
System.out.println(p.getFileLocation());
}
}