2015-02-11 59 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

相关问题