当我运行这段代码时,文件被创建,但它是空的,尽管输出看起来还可以
import java.io.IOException;
public class JasonTest {
public static void main(String[] args) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
TestJson tj = new TestJson(13, "kuku");
gson.toJson(tj, new FileWriter("test.json"));
System.out.println(gson.toJson(tj));
}
}
输出:
{
"num": 13,
"text": "kuku"
}
Process finished with exit code 0
1条答案
按热度按时间0vvn1miw1#
看这个问题。你需要关门
FileWriter
(如果目前无法关闭,则冲洗)。就像:或者更好地使用try/resources: