spring java 读取资源文件
< 返回列表时间: 2020-07-03来源:OSCHINA
springboot读取classpath下的文件方法
获取文件或流 this . getClass ( ) . getResource ( "/" ) + fileName ; this . getClass ( ) . getResourceAsStream ( fileName ) ;
获取文件 File file = org . springframework . util . ResourceUtils . getFile ( "classpath:test.txt" ) ;
获取文件或流 ClassPathResource classPathResource = new ClassPathResource ( "test.txt" ) ; classPathResource . getFile ( ) ; classPathResource . getInputStream ( ) ;
下面方法可以读取jar包下文件 InputStream io = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( "test.txt" ) ; InputStream io = ClassLoader . getSystemResourceAsStream ( "test.txt" ) ;
获取跟目录 File path = new File ( ResourceUtils . getURL ( "classpath:" ) . getPath ( ) ) ; if ( ! path . exists ( ) ) path = new File ( "" ) ; System . out . println ( "path:" + path . getAbsolutePath ( ) ) ;
如果上传目录为/static/images/upload/,则可以如下获取: File upload = new File ( path . getAbsolutePath ( ) , "static/images/upload/" ) ; if ( ! upload . exists ( ) ) upload . mkdirs ( ) ; System . out . println ( "upload url:" + upload . getAbsolutePath ( ) ) ; * 在开发测试模式时,得到的地址为:{项目跟目录}/target/static/images/upload/ * 在打包成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/
热门排行