本帖最后由 王超举 于 2017-8-18 10:14 编辑
web项目使用,类加载器读文件、servletContext对象读文件区别
1、servletContext有getResourceAsStream根据文件获取输入流、getRealPath根据文件获取绝对路径方法,servletContext获取的是tomcat发布的工程目录下,
即E:\软件\work\apache-tomcat-7.0.40\webapps\store_v2.0路径下。
2、类加载器只有getResourceAsStream根据文件获取输入流方法,获取的路径在tomcat发布的工程项目下WEB-INF下class路径,
即E:\软件\work\apache-tomcat-7.0.40\webapps\store_v2.0\WEB-INF\classes路径下。
以下为代码实例,说明:代码中的db.properties文件位于工程的src目录下
[Java] 纯文本查看 复制代码 /**
* 使用ServletContext中的getResourceAsStream读取.
* @throws FileNotFoundException
* @throws IOException
*/
private void test2() throws FileNotFoundException, IOException {
// 获得ServletContext:
ServletContext context = this.getServletContext();
InputStream is = context.getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(is);
String driverClass = properties.getProperty("driverClass");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println(driverClass);
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
/**
* 使用ServletContext中的getRealPath读取.
* @throws FileNotFoundException
* @throws IOException
*/
private void test3() throws FileNotFoundException, IOException {
// 获得ServletContext:
ServletContext context = this.getServletContext();
String realPath = context.getRealPath("/WEB-INF/classes/db.properties");
// 获得该文件的磁盘绝对路径.
System.out.println(realPath);
InputStream is = new FileInputStream(realPath);
Properties properties = new Properties();
properties.load(is);
String driverClass = properties.getProperty("driverClass");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println(driverClass);
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
/**
* 使用类的加载器来读取文件
* @throws IOException
*/
public static void readFile() throws IOException{
// 使用类的加载器来读取文件.
// 类的加载器用来加载class文件,将class文件加载到内存.
InputStream is = ReadFileUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(is);
String driverClass = properties.getProperty("driverClass");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println(driverClass);
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
|