Java工程读取项目下文件,使用的是相对路径,相对JVM路径
private void readFile() throws FileNotFoundException, IOException {
//获取文件输入流
InputStream is = new FileInputStream("src/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");
}
WEB工程读取项目下文件,相对与JVM路径,此时JVM已交给Tomcat管理
private void readFile(HttpServletRequest request) throws FileNotFoundException, IOException {
ServletContext context = request.getSession().getServletContext();
//方法一.直接获取文件输入流
/*InputStream is = context.getResourceAsStream("/WEB-INF/classes/db.properties");*/
//方法二.获得该文件的磁盘绝对路径
String realPath = context.getRealPath("/WEB-INF/classes/db.properties");
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");
}
request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了。
getRealPath("/") 获取实际路径,“/”指代项目根目录,所以返回的是项目在容器中的实际发布运行的根路径。
使用类加载器读取文件
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");
}