使用Class的getResourceAsStream("文件路径")方法读取配置文件
文件路径如果不以/开始则表示调用这个方法的类所在的目录
文件路径如果以/开始则表示工程根目录
* java工程根目录:workspace/工程/bin/
* web工程:tomcat/webapps/WEB-INF/classes/
* maven工程
* jar工程:workspace/工程/target/classes/
* war工程:tomcat/webapps/WEB-INF/classes/
JAVA工程
读取配置文件
public class MyTest {
public static void main(String[] args) throws IOException {
// InputStream in = MyTest.class.getResourceAsStream("a.properties");
InputStream in = MyTest.class.getResourceAsStream("/b.properties");
Properties p = new Properties();
p.load(in);
System.out.println(p.get("key"));
}
}
WEB工程
读取配置文件
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
InputStream in = MyServlet.class.getResourceAsStream("a.properties");
// InputStream in = MyTest.class.getResourceAsStream("/b.properties");
Properties p = new Properties();
p.load(in);
System.out.println(p.get("key"));
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
doGet(request, response);
}
}
Maven工程
读取配置文件
public class MyTest {
public static void main(String[] args) throws IOException {
// InputStream in = MyTest.class.getResourceAsStream("a.properties");
InputStream in = MyTest.class.getResourceAsStream("/b.properties");
Properties p = new Properties();
p.load(in);
System.out.println(p.get("key"));
}
}