Object 对象写入文件变成Json格式
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public void generateJson(Object obj) {
ObjectMapper mapper = new ObjectMapper();
try {
byte[] context = mapper.writeValueAsString(obj).getBytes(StandardCharsets.UTF_8);
FileUtils.writeByteArrayToFile(new File("target/test.json"), context);
} catch (IOException e) {
e.printStackTrace();
}
}
FilePath :
"target/test.json" --> 项目根目录下, 与项目子模块同层级
"/test.json" --> 会报错,java.io.filenotfoundexception: /test.json (read-only file system) ; 此时表示在根目录,并没有权限写入,可去掉“/”, 则在项目模块同层级上