标签:
1、一般工程中使用I/O类指定文件的绝对路径读取
FileInputStream fis = new FileInputStream("src/main/resources/zsm.properties"); ppt.load(fis); String memAddr1 = ppt.getProperty("memAddr1");
2、Web工程中可以使用ServletContext或ClassLoader来读取
2.1、通过ServletContext来读取资源文件,文件路径是相对于web项目(如JspServletFeature)根路径而言的。
2.2、通过ClassLoader来读取,文件路径是相对于类目录而言的(maven工程中一般为classes)
示例如下
(1)文件位置
(2)代码
// 使用servletContext读取资源文件,相对于web项目的根路径(即JspServletFeature) out.println("\n使用servletContext读取资源文件,相对于web项目的根路径(即JspServletFeature):"); readFileByServletContext(response, "FileReadFile1.properties"); readFileByServletContext(response, "/FileReadFile1.properties"); readFileByServletContext(response, "WEB-INF/classes/FileReadFile2.properties"); readFileByServletContext(response, "/WEB-INF/classes/FileReadFile2.properties"); readFileByServletContext(response, "WEB-INF/classes/com/zsm/util/FileReadFile3.properties"); readFileByServletContext(response, "/WEB-INF/classes/com/zsm/util/FileReadFile3.properties"); // 使用ClassLoader读取资源文件,相对于类目录(即classes) out.println("\n使用ClassLoader读取资源文件,相对于类目录(即classes):"); readFileByClassLoader(response, "../../FileReadFile1.properties"); readFileByClassLoader(response, "/../../FileReadFile1.properties"); readFileByClassLoader(response, "FileReadFile2.properties"); readFileByClassLoader(response, "/FileReadFile2.properties"); readFileByClassLoader(response, "com/zsm/util/FileReadFile3.properties"); readFileByClassLoader(response, "/com/zsm/util/FileReadFile3.properties"); // 使用servletContext读取资源文件,相对于web项目的根路径(即JspServletFeature) synchronized void readFileByServletContext(HttpServletResponse response, String filePath) throws IOException { InputStream in = this.getServletContext().getResourceAsStream(filePath); Properties prop = new Properties(); prop.load(in); String fileName = prop.getProperty("fileName"); String name = prop.getProperty("name"); String company = prop.getProperty("company"); in.close(); response.getWriter().println(MessageFormat.format("filePath={0}, fileName={1}, name={2}, company={3}", filePath, fileName, name, company)); } // 使用ClassLoader读取资源文件,相对于类目录(即classes) synchronized void readFileByClassLoader(HttpServletResponse response, String filePath) throws IOException { // 获取到装载当前类的类装载器 ClassLoader loader = FileReadServlet.class.getClassLoader(); InputStream in = loader.getResourceAsStream(filePath); Properties prop = new Properties(); prop.load(in); String fileName = prop.getProperty("fileName"); String name = prop.getProperty("name"); String company = prop.getProperty("company"); in.close(); response.getWriter().println(MessageFormat.format("filePath={0}, fileName={1}, name={2}, company={3}", filePath, fileName, name, company)); }
(3)结果
标签:
原文地址:http://www.cnblogs.com/z-sm/p/5466955.html