2014-09-12 165 views
-1

方法以逗号分隔的格式返回字符串。例如,返回的字符串可以像下面给出的那样。Java:以字符串格式将CSV写入CSV文件

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 

我们怎么做呢?是否有任何开源库可以完成这项任务?

+2

为什么你需要一个额外的库来编写文本文件?只需将文件头写入文件,并且由于您的字符串已经有换行符,只需将该字符串写入文件即可。 – forgivenson 2014-09-12 11:28:24

回答

1

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

0

你可以使用它作为一个学习的例子。 我使用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 
     } 
     } 
    } 
    } 
} 
0

这是非常简单的

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块和处理异常