我正在研究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()
造成的,它可能会将每个记录都写为“ ...”。还有其他方法可以达到相同目的吗?我可以使用提到的“数据”列表来实现此目的吗?
最佳答案
可以使用writeNext(String[] nextLine, boolean applyQuotesToAll)代替writeNext(String[]);
,它将仅对包含特殊字符的值添加引号。
另外,我认为循环存在问题,我认为应该是这样的:
for(int c = 0; c <= entries.length - 6; c+=6 ){
subentries = Arrays.copyOfRange(entries, c, c+6) ;
writer.writeNext(subentries, false);
}
关于java - 在Java中以CSV文件写入子字符串的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34322500/