在java中读取csv文件并写入新文件

问题描述 投票:0回答:1

我正在从url读取csv文件,并将此文件复制到新的csv文件。

这个csv文件是-分开的。我用-取代,

读取10 MB以上的大文件需要两倍的时间。我可以用什么来将-分隔文件转换为,分隔文件?

URL url = null;
try {
    url = new URL(info.getUrl());
} catch (MalformedURLException e1) {
    e1.printStackTrace();
}
Scanner scanner = null;
StringBuilder sb = new StringBuilder();
scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
    String line = scanner.nextLine();
    sb.append(line.replace(",", "-").replace("|", ","));
    sb.append("\n");
}
java string csv replace
1个回答
0
投票

使用univocity-parsers,您只需要:

//configure the input format
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setDelimiter('-');

//configure the ouput format
CsvWriterSettings writerSettings = new CsvWriterSettings();
writerSettings.getFormat().setDelimiter(',');

//use a class for common pre-made routines used for dealing with CSV
CsvRoutines csvRoutines = new CsvRoutines(parserSettings, writerSettings);

//use the `parseAndWrite` method to read the input in a given format and write it back to another.
csvRoutines.parseAndWrite(new FileReader("/path/to/input.csv"), new FileWriter("/path/to/output.csv"));

希望这可以帮助

免责声明:我是这个图书馆的作者。它是开源和免费的(Apache 2.0许可证)

© www.soinside.com 2019 - 2024. All rights reserved.