快捷搜索: 王者荣耀 脱发

一行日志,让整个文件导出服务导出内容都为空..

问题

直接上代码,看看有无眼尖的小伙伴发现问题:

// 设置参数
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
FileSystemResource resource = new FileSystemResource(file);
param.set("token", "XXXXXX");
param.set("file", resource);
LOGGER.info("开始文件上传: {}", JSONObject.toJSONString(param));
httpsRestTemplate.postForObject(uploadParam.getUrl(), param, HashMap.class);
LOGGER.info("文件上传结束");

分析

本人企图在上传文件的时候,把请求参数打印出来(为了分析问题),输出方式用 FastJSON 中的方法**JSONObject.toJSONString()**序列化了一下参数 。在实际导出的过程中,发现所有导出导出的文件内容为空,百思不得其姐。

于是进入 toJSONString() 方法,一路Debug进来,到了ListSerializer 这里,如下图: itemSerializer这里实际对象是ASMSerializer(关于这玩意,查了一些资料,在FastJSON中使用它来实现反射),而在处理反射的过程中,会调用get方法获取属性值执行序列化。

而在FileSystemResource 中,关于OutputStream 的获取,是会重新new一个FileOutputStream,再往方法里面看,发现了append属性为false,相当于按原来的路径重新写入了一个新文件,而且是不追加的方式。到这里也算明白了为啥我的文件导出来都为空了。

//

public class FileSystemResource extends AbstractResource implements WritableResource {
          
   
 //....

public OutputStream getOutputStream() throws IOException {
          
   
        return new FileOutputStream(this.file);
    }

}

public FileOutputStream(File file) throws FileNotFoundException {
          
   
        this(file, false);
    }

public FileOutputStream(File file, boolean append)
        throws FileNotFoundException
    {
          
   
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
          
   
            security.checkWrite(name);
        }
        if (name == null) {
          
   
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
          
   
            throw new FileNotFoundException("Invalid file path");
        }
        this.fd = new FileDescriptor();
        fd.attach(this);
        this.append = append;
        this.path = name;

        open(name, append);
    }

小结

    JSONObject.toJsonString 使用还是得慎重 复杂对象序列化时,特别是一些框架封装的对象还是得多多留意
经验分享 程序员 微信小程序 职场和发展