簡體   English   中英

在Java中讀取CSV文件並寫入新文件

[英]Reading csv file in java and write in new file

我正在從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");
}

使用univocity解析器,您所需要做的就是:

//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許可證)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM