简体   繁体   English

BufferedWriter无法正确写入JSON字符串

[英]BufferedWriter doesnt write JSON String correctly

I wrote a code that gets a JSON text from a website and formats it so it is easier to read. 我编写了一个代码,该代码从网站获取JSON文本并对其进行格式化,以便于阅读。 My problem with the code is: 我的代码问题是:

public static void gsonFile(){
  try {
    re = new BufferedReader(new FileReader(dateiname));
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser jp = new JsonParser();
    String uglyJSONString ="";
    uglyJSONString = re.readLine();
    JsonElement je = jp.parse(uglyJSONString);  
    String prettyJsonString = gson.toJson(je);
    System.out.println(prettyJsonString);

    wr = new BufferedWriter(new FileWriter(dateiname));
    wr.write(prettyJsonString);

    wr.close();
    re.close();

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

It correctly prints it into the console : http://imgur.com/B8MTlYW.png 它将正确地打印到控制台中: http : //imgur.com/B8MTlYW.png

But in my txt file it looks like this: http://imgur.com/N8iN7dv.png 但是在我的txt文件中,它看起来像这样: http : //imgur.com/N8iN7dv.png

What can I do so it correctly prints it into the file? 我该怎么做才能正确将其打印到文件中? (separated by new lines) (用新行分隔)

Gson uses \\n as line delimiter (as can be seen in the newline method here ). GSON使用\\n作为行定界符(如可以在可看出newline的方法在这里 )。

Since Notepad does not understand \\n you can either open your result file with another file editor ( Wordpad , Notepad++ , Atom , Sublime Text , etc.) or replace the \\n by \\r\\n before writing it: 由于记事本无法理解\\n您可以使用另一个文件编辑器( WordpadNotepad ++AtomSublime Text等)打开结果文件,或在写入之前用\\r\\n替换\\n

prettyJsonString = prettyJsonString.replace("\n", "\r\n");

FileReader and FileWriter are old utility classes that use the platform encoding. FileReader和FileWriter是使用平台编码的旧实用程序类。 This gives non-portable files. 这给出了不可移植的文件。 And for JSON one ordinarily uses UTF-8. 对于JSON,通常使用UTF-8。

Path datei = Paths.get(dateiname);
re = Files.newBufferedReader(datei, StandardCharsets.UTF_8);

Or 要么

List<String> lines = Files.readAllLines(datei, StandardCharsets.UTF_8);
// Without line endings as usual.

Or 要么

String text = new String(Files.readAllBytes(datei), StandardCharsets.UTF_8);

And later: 然后:

Files.write(text.getBytes(StandardCharsets.UTF_8));

It is problem with your text editor. 您的文本编辑器有问题。 Not with text. 不带文字。 It incorrectly process new line character. 它错误地处理换行符。

I suppose it expect CR LF (Windows way) symbols and Gson generate only LF symbol (Unix way). 我想它期望CR LF (Windows方式)符号和Gson仅生成LF符号(Unix方式)。

After a quick search this topic might come handy. 快速搜索后,该主题可能会派上用场。

Strings written to file do not preserve line breaks 写入文件的字符串不保留换行符

Also, opening in another editor like the others said will help too 另外,像其他人所说的那样在另一个编辑器中打开也将有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM