web项目读取resource目录下的资源

本地读取资源文件

1.方式

File file = new File("src/main/resources/properties/basecom.properties"); InputStream in = new FileInputStream(file); 如果工程部署到Tomcat中时,按照上边方式,则会出现找不到该文件路径的异常。经搜索资料知道,Java工程打包部署到Tomcat中时,properties的路径变到顶层(classes下):

并且,此时读取文件需要采用流(stream)的方式读取,如下: InputStream in = this.getClass().getResourceAsStream("/properties/basecom.properties"); 其中properties前的斜杠,相对于调用类,共同的顶层路径。

服务器tomcat获取文件

获取服务器目录

springboot项目读取 resources 目录下的文件的9种方式(总结):

方式10

需要request,不是一种好的方式

String filePath = "ident/static/file/"+nowTimeStr+"/";
String realPath = request.getSession().getServletContext().getRealPath(filePath);

服务器jar包获取文件

如目录结构

public static String readSqlFile(String fileDir, String fileName) {
    	ClassPathResource cpr = new ClassPathResource(fileDir+fileName);
    	StringBuffer result = new StringBuffer();
		try (BufferedReader br = new BufferedReader(new InputStreamReader(cpr.getInputStream()))) {
		    String line = null;
		    while((line = br.readLine()) != null) {
		    	if(line.startsWith("--") ) { //|| StringUtils.isBlank(line)
            		continue;
            	}
                result.append(line);
                result.append(System.getProperty("line.separator"));
		    }
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return result.toString();
	}


main {
    readSqlFile("sql/,"first.txt")
}
经验分享 程序员 微信小程序 职场和发展