org.springframework.core.io.ClassPathResource读取文件

//假设有src/main/resources/xmlTemplate/data.xml,那filePath写法为xmlTemplate/data.xml
//程序打jar包后,一般的读取方式不可取,因为文件是在jar包中,无法对应文件系统上的路径,但ClassPathResource类可以
public static String classpathXmlToStr(String filePath) {
		
		StringBuffer xml = new StringBuffer();
		
		ClassPathResource resource = new ClassPathResource(filePath);
		try(InputStream in = resource.getInputStream()){
			
			//文本文件转为字符串
			int len=0;
			byte[] b=new byte[1024];
			while((len=in.read(b))!=-1){
				xml.append(new String(b,0,len));
			}
		} catch (IOException e) {
			LogUtil.error("xml文件转字符串异常!",e);
		}
			
			
		return xml.toString();
		
	}
发布了89 篇原创文章 · 获赞 67 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/xl_1803/article/details/99677731
今日推荐