java 读取src 和 web 路径下的配置文件的方法
程序员文章站
2022-03-11 20:01:48
...
读取src路径下的druid.properties文件
方式一:使用 FileInputStream 读取文件
//使用 FileInputStream 读取文件
//该方式可以读取任意路径下的配置文件。
@Test
public void func1(){
try {
InputStream is = new FileInputStream("src/druid.properties");
Properties prop = new Properties();
prop.load(is);
String value = prop.getProperty("driverClassName");
System.out.println("value: "+value);
} catch (Exception e) {
e.printStackTrace();
}
}
方式二:使用 getResourceAsStream 读取文件
//使用 getResourceAsStream 读取文件
//该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。
@Test
public void func2(){
try {
InputStream is = MyTest.class.getClassLoader().getResourceAsStream("druid.properties");
Properties prop = new Properties();
prop.load(is);
String value = prop.getProperty("driverClassName");
System.out.println("value: "+value);
} catch (Exception e) {
e.printStackTrace();
}
}
方式三:使用 ResourceBundle 读取文件
//使用 ResourceBundle 读取文件
//优点:没有异常,读取文件后 可以直接通过key获取value
//缺点:只能加载类classes下面的资源文件,且只能读取.properties文件。
@Test
public void func3(){
ResourceBundle bundle = ResourceBundle.getBundle("druid");//没有后缀名.properties
String value = bundle.getString("driverClassName");
System.out.println(value);
}
读取web 路径下img文件夹下druid.properties的资源
@WebServlet("/MyServletTest")
public class MyServletTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//方式一:读取web下资源
InputStream is = getServletContext().getResourceAsStream("/img/druid.properties");
Properties prop = new Properties();
prop.load(is);
String username = prop.getProperty("username");
System.out.println("username: "+username);
String realPath = getServletContext().getRealPath("");
System.out.println("realpath: "+realPath);
//realpath: F:\IdeaProjects\JAVAEE\out\artifacts\properties_demo_war_exploded\
//方式二:部署后动态路径获取web下的资源
String path = this.getServletContext().getRealPath("/img/druid.properties");
FileInputStream fis = new FileInputStream(path);
prop.load(fis);
username = prop.getProperty("username");
System.out.println("username: "+username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}