使用子字符串在Java中写入CSV文件时出现问题

时间:2015-12-16 21:31:45

标签: java string list arraylist

我正在研究一个java项目。我在Win7上使用带有eclipse的JDK1.7。 我有一个包含以下记录的.csv文件:

317213,384641,1,Closed,-119,-1
317246,317247,1,Closed,8.8,-0.2
317264,317246,1,Closed,92.3,-7.2
317264,317246,2,Open,0,0

此外,我从文件中提取这些记录,更新记录,再次存储在文件中。当我获取更新的记录时,我得到以下输出:

"317213","384641","1","Closed","-118.9","-1.0"
"317246","317247","1","Closed","20.8","-0.1"
"317264","317246","1","Closed","104.1","-5.4"
"317264","317246","2","Open","0.0","0.0"

显然,问题在记录的每个字段中都是“......”。

这是我的代码:

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;

address = path + "/networkFile/1/11/B20branch1t.csv" ;
CSVWriter writer = new CSVWriter(new FileWriter(address));
List<String[]> data = new ArrayList<String[]>();
String[] subentries = {}; 
String answer = "317213,384641,1,Closed,-119,-1,317246,317247,1,Closed,8.8,-0.2,317264,317246,1,Closed,92.3,-7.2,317264,317246,2,Open,0,0";

String[] entries = answer.split(",");
for( c = 0 ; c < entries.length ; c+=6 ) 
{
    subentries = Arrays.copyOfRange(entries, c, c+6) ; 
}
writer.writeNext(subentries);
writer.close();

问题可能是因为writer.writeNext(),可能会用“......”写下每条记录。 是否有其他方法可以实现相同的目标?我可以使用提到的“数据”列表来实现这一目标吗?

2 个答案:

答案 0 :(得分:1)

您可以使用writeNext(String[] nextLine, boolean applyQuotesToAll)代替writeNext(String[]);,而json2csharp只会为包含特殊字符的值添加引号。

另外,我认为循环存在问题,我认为它应该是这样的:

for(int c = 0; c <= entries.length - 6; c+=6 ){
    subentries = Arrays.copyOfRange(entries, c, c+6) ; 
    writer.writeNext(subentries, false);
}

答案 1 :(得分:0)

它对我有用!

writer.writeNext(subentries, false);

谢谢@ S.L。 Barth @Shadow