1. 问题
有个功能需要调用一个传输文件的api,使用FileSystemResource
进行传输,在调用api之前使用JSONObject.toJSONString()
输出一下log之后 发现每次输出log之后本地文件就会变成0KB
2. 分析
FileSystemResource
是spring封装的类,其实现了WritableResource接口
public class FileSystemResource extends AbstractResource implements WritableResource {...}
在递归解析字段时,由于是采用getter方式,getOutputStream
被当做getter方法被调用,
public interface WritableResource extends Resource {
// omit
/**
* Return an {@link OutputStream} for the underlying resource,
* allowing to (over-)write its content.
* @throws IOException if the stream could not be opened
* @see #getInputStream()
*/
OutputStream getOutputStream() throws IOException;
}
getXX
本意是获取XX
字段的值,但getOutputStream()
被调用,拿到output后未写入任何值,相当于向output写入了空,后被flush到磁盘导致的文件被重写了
3. 解决
- 不要toJsonString打印复杂对象,特别是不熟悉的class
- 避免使用
FileSystemResource
类,使用其他对象代替
4. 参考资料
https://github.com/alibaba/fastjson/issues/3436
https://github.com/alibaba/fastjson/issues/3547#issuecomment-728782084