【发布时间】:2017-06-06 10:45:32
【问题描述】:
我正在尝试读取 HashMap 并写入 CSV 文件。我正在使用CSVPrinter,但我的方法没有返回 CSV 文件。
这是我使用的代码: 编辑代码
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
public class SJV{
public File writeCSV(Map featureSet) throws IOException{
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
Map<String, Integer> map = featureSet;
File temp = File.createTempFile("tempfile", ".tmp");
FileWriter fs = new FileWriter(temp);
CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
//csvFilePrinter.printRecord(FILE_HEADER);
csvFilePrinter.printRecord(map.keySet().toArray());
csvFilePrinter.printRecord(map.values().toArray());
csvFilePrinter.close();
fs.close();
return temp;
}
}
这是我的测试:
public void testWriteCSV() throws IOException {
SJV sj = new SJV();
HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);
File fs = sj.writeCSV(hmap);
if (fs.exists()){
Scanner input = new Scanner(fs );
while (input.hasNextLine())
{
System.out.println(input.nextLine());
}
input.close();
}
我真的不明白为什么该方法没有返回 CSV 文件。
【问题讨论】:
-
缺少一点代码。
sj是什么?有什么写的吗?有什么错误吗? -
返回什么方法而不是 CSV 文件?
-
我认为您没有关闭文件。
-
@Kumaresp 不,实际上,这不是另一个问题。这可能是您遇到问题的原因。尝试纠正它。
-
请edit你的问题,并把你的新版本关闭。