[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);
}