将JSON写入文件

  • 首先需要引入fastjson的依赖文件,以下是maven的依赖:

     
      
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
    </dependency>
  • 然后是将json字符串写到文件中去:

       
    
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.serializer.SerializerFeature;
     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.nio.charset.StandardCharsets;
     
    public class JsonUtils {
     
        private static final String DEFAULT_SAVE_DIRECTORY = "upload/file/";
    
        private static String SEPARATOR = File.separator;
    
        private static SimpleDateFormat DateSdf = new SimpleDateFormat("yyyyMMdd");
    
        public static void saveJson(JSONObject data,Long taskId,Long cmdId) {
    
    //写入操作
            String content = JSON.toJSONString(data, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat);
            String filePath =DEFAULT_SAVE_DIRECTORY+ getStrDate() +"/"+ "taskId-"+taskId+"cmdId-"+cmdId+".txt";
            try {
                File file = new File(filePath);
                // 创建上级目录
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                // 如果文件存在,则删除文件
                if (file.exists()) {
                    file.delete();
                }
                // 创建文件
                file.createNewFile();
                // 写入文件
                Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
                write.write(content);
                write.flush();
                write.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static String getStrDate() {
            return DateSdf.format(new Date());
        }
    }