【问题标题】:Java : Writing CSV in String format to CSV in a fileJava:将字符串格式的CSV写入文件中的CSV
【发布时间】:2014-09-12 11:25:24
【问题描述】:

方法返回逗号分隔格式的字符串。例如,返回的字符串可以如下所示。

Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China

我需要获取此字符串并将其写入 CSV 文件。我还必须为此文件插入页眉和页脚。

例如,当我打开文件时,上述数据的内容将是

Name,Age,Gender,Country
Tarantino,50,M,USA    
Carey Mulligan,27,F,UK
Gong Li,45,F,China

我们如何做到这一点?是否有任何开源库来执行此任务?

【问题讨论】:

  • 为什么需要额外的库来将文本写入文件?只需将标题写入文件,由于您的字符串已经有换行符,只需将字符串写入文件即可。

标签: java csv file-io


【解决方案1】:

CSV 格式的定义不是很好。您不必为文件编写标题。相反,它是非常简单的格式。数据值使用逗号或分号或空格等分隔。 您只需编写自己的简单方法,使用 java.io 包中的 FileOutputStream 或 Writer 将字符串写入本地计算机上的文件。

【讨论】:

    【解决方案2】:

    您可以将此作为学习示例。 我使用了BufferedReader,因为他会处理line 分隔符,但您也可以使用#split 方法,并写入生成的标记。

    import java.io.*;
    
    public class Tests {
    
      public static void main(String[] args) {
    
        File file = new File("out.csv");
        BufferedWriter out = null;
    
        try {
    
          out = new BufferedWriter(new FileWriter(file));
    
          String string = "Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China";
    
          BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(string.getBytes())));
          String line;
    
          while ((line = reader.readLine()) != null) {
            out.write(line.trim());
            out.newLine();
          }
        }
    
        catch (IOException e) {
          // log something
          e.printStackTrace();
        }
    
        finally {
          if (out != null) {
            try {
              out.close();
            } catch (IOException e) {
              // ignored
            }
          }
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      这很简单

      String str = "Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China";
      PrintWriter  pr = new PrintWriter(new FileWriter(new File("test.csv"), true));
      String arr[] = str.split("\\n"); 
      // splited the string by new line provided with the string
      pr.println("Name,Age,Gender,Country"); 
      // header written first and rest of data appended
      for(String s : arr){
          pr.println(s);
      }
      pr.close();
      

      不要忘记在 finally 块中关闭流并处理异常

      【讨论】:

        猜你喜欢
        • 2015-07-16
        • 2016-06-15
        • 2016-10-22
        • 1970-01-01
        • 2012-07-29
        • 1970-01-01
        • 2018-06-26
        • 2015-12-14
        • 1970-01-01
        相关资源
        最近更新 更多