2015-02-11 64 views
0

我是Java中的數據庫的新手,我試圖導出1表中的數據並將其存儲在文本文件中。目前下面的代碼寫入文本文件,但全部在一行?誰能幫忙?我如何從數據庫獲取數據並將其存儲到文本文件中?

我的代碼

private static String listHeader() { 
      String output = "Id Priority From       Label Subject\n"; 
      output += "== ======== ====       ===== =======\n"; 
      return output; 
     } 
    public static String Export_Message_Emails() { 
      String output = listHeader(); 
      output +="\n"; 
      try { 
       ResultSet res = stmt.executeQuery("SELECT * from messages ORDER BY ID ASC"); 
       while (res.next()) { // there is a result 
        output += formatListEntry(res); 
        output +="\n"; 

       } 
      } catch (Exception e) { 
       System.out.println(e); 
       return null; 
      } 
      return output; 
     } 
public void exportCode(String File1){ 
    try { 
       if ("Messages".equals(nameOfFile)){ 
       fw = new FileWriter(f); 
       //what needs to be written here 
       //fw.write(MessageData.listAll()); 
       fw.write(MessageData.Export_Message_Emails()); 
        fw.close(); 

      } 
} 

回答

3

不要使用 「\ n」 的硬編碼值。而是使用System.getProperty("line.separator");或者如果您使用的是Java 7或更高版本,則可以使用System.lineSeparator();

+0

我在哪裏編寫System.llineSeparator(); – 2015-02-11 12:59:30

+1

而不是輸出+ =「\ n」寫輸出+ = System.lineSeparator() – 2015-02-11 13:02:09

0

嘗試String.format("%n")而不是"\n"

0

我會假設你使用的是Windows,並且你正在用記事本打開你的文件。如果這是正確的,那麼你的輸出並不是一個真正的問題,而是用你正在查看的編輯器。

  1. 嘗試一個更好的編輯器,即。記事本+
  2. 做其他答案建議和使用System.getProperty(「line.separator」);或類似的。
  3. 使用Writer實現,例如PrintWriter。

就個人而言,我更喜歡系統行分隔符「\ n」,它在Windows上是「\ r \ n」。

編輯:(!這是完全正常的,當然)添加選項3

+0

如果換行符有可能是「\ r \ n」,那麼爲什麼要硬編碼「\ n」它可能是與從系統本身拉出換行符錯誤? – Ascalonian 2015-02-11 13:04:09

+0

嗯,只是因爲系統的奧術原因使用特定的行分隔符並不意味着你**必須**使用它。我經常嘗試使用「\ n」,即使我在Windows上(我安裝了Eclipse,Git等以使用Unix風格)。 – 2015-02-12 14:14:50

相關問題