Loading... ## 1. 问题 有个功能需要调用一个传输文件的api,使用`FileSystemResource`进行传输,在调用api之前使用`JSONObject.toJSONString()`输出一下log之后 发现每次输出log之后本地文件就会变成0KB ## 2. 分析 `FileSystemResource` 是spring封装的类,其实现了WritableResource接口 ```java position-relative overflow-auto public class FileSystemResource extends AbstractResource implements WritableResource {...} ``` 在递归解析字段时,由于是采用getter方式,`getOutputStream`被当做getter方法被调用, ```java position-relative overflow-auto 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. 解决 1. 不要toJsonString打印复杂对象,特别是不熟悉的class 2. 避免使用`FileSystemResource`类,使用其他对象代替 ## 4. 参考资料 https://github.com/alibaba/fastjson/issues/3436 https://github.com/alibaba/fastjson/issues/3547#issuecomment-728782084 Last modification:April 19, 2022 © Reprinted from other stations Support Appreciate the author AliPayWeChat Like 0 感谢大佬投喂 啾咪~