敲黑板了 这篇文章别看代码写的非常整洁 千万别用这种方案 是坑 在生产环境下会报空文件异常
java. io. FileNotFoundException: class path resource [ test. txt] cannot be resolved to absolute file path because it does not reside in the file system: jar: file: / E : / project/ usb- key. jar! / BOOT - INF / classes! / test. txt
at org. springframework. util. ResourceUtils. getFile ( ResourceUtils . java: 217 )
at org. springframework. util. ResourceUtils. getFile ( ResourceUtils . java: 180 )
解决思路
从json文件中读取数据
使用spring的ResourceUtils读取文件 使用apache.commons.io将文件转换成String 使用fastjson将String序列化对象
向json文件中写入数据
使用spring的ResourceUtils得到文件 使用fastjson将json对象转换成String 使用apache.commons.io将String写入到文件
maven依赖
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> fastjson</ artifactId>
< version> 1.2.79</ version>
</ dependency>
< dependency>
< groupId> commons-io</ groupId>
< artifactId> commons-io</ artifactId>
< version> 2.11.0</ version>
</ dependency>
封装工具类
public class JsonFileUtils {
private final static Logger logger = LoggerFactory . getLogger ( JsonFileUtils . class ) ;
public static ReqAuthEntity readDataFromJson ( ) {
File file = null ;
try {
file = ResourceUtils . getFile ( "classpath:sysconfig.json" ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
logger. error ( "读取json文件时文件路径获取失败" ) ;
}
String json = null ;
try {
json = FileUtils . readFileToString ( file, "UTF-8" ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
logger. error ( "读取json文件内容失败" ) ;
}
ReqAuthEntity reqAuth = JSONObject . parseObject ( json, ReqAuthEntity . class ) ;
return reqAuth;
}
public static boolean writeDataToJson ( String content) {
File file = null ;
try {
file = ResourceUtils . getFile ( "classpath:sysconfig.json" ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
logger. error ( "获得系统参数配置文件异常" ) ;
return false ;
}
try {
FileUtils . writeStringToFile ( file, content, "UTF-8" ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
logger. error ( "向系统参数配置文件中写入数据异常" ) ;
return false ;
}
return true ;
}
}
磁盘文件位置