如何在写入文件时使用漂亮的打印?
package tests;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
public class Try06 {
public static class V {
double x, y;
}
public static void main(String[] args) throws IOException {
GsonBuilder gb = new GsonBuilder();
gb = gb
.setPrettyPrinting()
.setVersion(1.0)
;
Gson gson0 = gb.create();
File file = new File("D:\\test.json");
System.out.println(gson0.toJson(new V()));
JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(file)));
gson0.toJson(new V(), V.class, writer);
writer.flush();
writer.close();
}
}
我也注意到,如果没有刷新,该文件是空的。它应该在退出时冲洗吗?
答案 0 :(得分:1)
显式设置非空字符串缩进有助于:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonWriter writer = new JsonWriter(new FileWriter(fileOut));
writer.setIndent(" "); // <-- without this the file is written without line-breaks and indents
gson.toJson(object, type, writer);
没有时间检查Gson来源,可能还有另一种解决方法。
答案 1 :(得分:0)
private void newline() throws IOException {
if (indent == null)
return;
out.write("\n"); //--- Your problem here!
int i = 1;
for (int size = stackSize; i < size; i++)
out.write(indent);
}
这部分源于JsonWriter类。由于使用字符串分隔符&#39; \ n&#39;。它适用于UNIX系统。但Windows用于新行&#39; \ r \ n&#39;。
如何解决您的问题?看看这个:
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
dos.writeBytes(gson0.toJson(new V()).replace("\n", "\r\n"));
dos.flush();
dos.close();
如果您想要系统独立的解决方案,那么替换&#34; \ r \ n&#34;通过这个:
System.getProperty("line.separator");
或由此:
System.lineSeparator();