簡體   English   中英

BufferedWriter無法正確寫入JSON字符串

[英]BufferedWriter doesnt write JSON String correctly

我編寫了一個代碼,該代碼從網站獲取JSON文本並對其進行格式化,以便於閱讀。 我的代碼問題是:

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();
}
}

它將正確地打印到控制台中: http : //imgur.com/B8MTlYW.png

但是在我的txt文件中,它看起來像這樣: http : //imgur.com/N8iN7dv.png

我該怎么做才能正確將其打印到文件中? (用新行分隔)

GSON使用\\n作為行定界符(如可以在可看出newline的方法在這里 )。

由於記事本無法理解\\n您可以使用另一個文件編輯器( WordpadNotepad ++AtomSublime Text等)打開結果文件,或在寫入之前用\\r\\n替換\\n

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

FileReader和FileWriter是使用平台編碼的舊實用程序類。 這給出了不可移植的文件。 對於JSON,通常使用UTF-8。

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

要么

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

要么

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

然后:

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

您的文本編輯器有問題。 不帶文字。 它錯誤地處理換行符。

我想它期望CR LF (Windows方式)符號和Gson僅生成LF符號(Unix方式)。

快速搜索后,該主題可能會派上用場。

寫入文件的字符串不保留換行符

另外,像其他人所說的那樣在另一個編輯器中打開也將有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM