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种方式(总结):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")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值