Java - 使用 Apache.commons.csv 编写 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36289043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Write CSV File with Apache.commons.csv
提问by jonbon
I'm using the apache.commons.csv library in Java. I'm reading a CSV file from a web page with this code:
我在 Java 中使用apache.commons.csv 库。我正在使用以下代码从网页读取 CSV 文件:
InputStream input = new URL(url).openStream();
Reader reader = new InputStreamReader(input, "UTF-8");
defaultParser = new CSVParser(reader, CSVFormat.DEFAULT);
excelParser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
defaultParsedData = defaultParser.getRecords();
excelParsedData = excelParser.getRecords();
However, I can't find a method in this library to easily write this file to my computer in order to open it up and read from it later on.
但是,我在这个库中找不到一种方法可以轻松地将此文件写入我的计算机,以便稍后打开它并从中读取。
I tried this code to save the file.
我试过这段代码来保存文件。
String outputFile = savePath+".csv";
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader();
FileWriter fileWriter = new FileWriter(outputFile);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
for (CSVRecord csvRecord : excelParser) {
for(String dataPoint: csvRecord){
csvFilePrinter.print(dataPoint);
}
csvFilePrinter.print('\n');
}
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
However, when I try to read the file with this code, nothing prints out:
但是,当我尝试使用此代码读取文件时,没有打印出任何内容:
InputStream input = new FileInputStream(cvsFilePath);
Reader reader = new InputStreamReader(input, "UTF-8");
CSVParser load = new CSVParser(reader, CSVFormat.EXCEL);
//TEST THAT IT WORKED
java.util.List<CSVRecord> testlist = load.getRecords();
CSVRecord dataPoint = testlist.get(0);
System.out.println("print: " + dataPoint.get(0));
This only prints out "print: " If I add
这只会打印出“打印:”如果我添加
System.out.println("print: " + dataPoint.get(1));
it gives a
它给出了一个
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1
When I open the saved CSV file with notepad there is a blank line and then:
当我用记事本打开保存的 CSV 文件时,有一个空行,然后:
2016-03-04,714.98999,716.48999,706.02002,710.890015,1967900,710.890015," ",2016-03-03,718.679993,719.450012,706.02002,712.419983,1956800,712.419983," ",2016-03-02,719.00,720.00,712.00,718.849976,1627800,718.849976,"
2016-03-04,714.98999,716.48999,706.02002,710.890015,1967900,710.890015, “ ”2016-03-03,718.679993,719.450012,706.02002,712.419983,1956800,712.419983,“”,2016-03-02,719.00,720.00,712.00,718.849976, 1627800,718.849976,"
回答by Arnaud
It looks like you are printing all the records on the same line .
看起来您正在同一行上打印所有记录。
Other methods like printRecordswill be more helpful :
其他方法如printRecords会更有帮助:
String outputFile = savePath+".csv";
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader();
FileWriter fileWriter = new FileWriter(outputFile);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecords(excelParser.getRecords());
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
回答by Basil Bourque
The Answer by Arnaudis correct and good. Here is a variation, shorter and more modern.
Arnaud的答案是正确和好的。这是一个变体,更短,更现代。
Here we:
在这里,我们:
- Use the
Path
,File
, andFiles
classes offered by modern Java to make easier work of file-handling. - Use a
BufferedWriter
for better performance with large amounts of data. - Specify the character encodingto be used. Usually UTF-8is the best. If you do not understand, read this.
- Include the necessary try-catchesfor file-related exceptions.
- Add try-with-resourcessyntax to auto-close the file.
- Skip the explicit flushing, as the buffered writer will be flushed automatically as part of auto-closing the
BufferedWriter
andCSVPrinter
. To quote the Javadoc, callingjava.io.Writer::close
“Closes the stream, flushing it first.”.
- 使用
Path
,File
以及Files
现代的Java提供的课程,以使文件处理工作更加容易。 - 在
BufferedWriter
处理大量数据时使用 a以获得更好的性能。 - 指定要使用的字符编码。通常UTF-8是最好的。如果您不明白,请阅读此内容。
- 包括必要的尝试捕获文件相关的异常。
- 添加try-with-resources语法以自动关闭文件。
- 跳过显式刷新,因为缓冲的写入器将作为自动关闭
BufferedWriter
和的一部分自动刷新CSVPrinter
。引用 Javadoc,调用java.io.Writer::close
“关闭流,首先刷新它。”。
Code:
代码:
CSVFormat format = CSVFormat.EXCEL.withHeader();
Path path = Paths.get( savePath + ".csv";
try (
BufferedWriter writer = Files.newBufferedWriter( path , StandardCharsets.UTF_8 ) ;
CSVPrinter printer = new CSVPrinter( writer , format ) ;
)
{
printer.printRecords( excelParser.getRecords() );
} catch ( IOException e )
{
e.printStackTrace();
}
回答by Ion Freeman
Have you tried flushing and closing the CSVPrinter, not the FileWriter?
您是否尝试过刷新和关闭 CSVPrinter,而不是 FileWriter?