gpt4 book ai didi

java - 适用于 Java 的优秀且有效的 CSV/TSV 阅读器

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:23 24 4
gpt4 key购买 nike

我正在尝试读取包含大约 1000000 行或更多行的大型 CSVTSV(制表符分隔)文件。现在我尝试读取包含 ~2500000 行的 TSVopencsv ,但它抛出一个 java.lang.NullPointerException。它适用于具有 ~250000 行的较小 TSV 文件。所以我想知道是否还有其他 Libraries 支持读取巨大的 CSVTSV 文件。你有什么想法吗?

所有对我的代码感兴趣的人(我把它缩短了,所以 Try-Catch 显然是无效的):

InputStreamReader in = null;
CSVReader reader = null;
try {
in = this.replaceBackSlashes();
reader = new CSVReader(in, this.seperator, '\"', this.offset);
ret = reader.readAll();
} finally {
try {
reader.close();
}
}

编辑:这是我构造 InputStreamReader 的方法:

private InputStreamReader replaceBackSlashes() throws Exception {
FileInputStream fis = null;
Scanner in = null;
try {
fis = new FileInputStream(this.csvFile);
in = new Scanner(fis, this.encoding);
ByteArrayOutputStream out = new ByteArrayOutputStream();

while (in.hasNext()) {
String nextLine = in.nextLine().replace("\\", "/");
// nextLine = nextLine.replaceAll(" ", "");
nextLine = nextLine.replaceAll("'", "");
out.write(nextLine.getBytes());
out.write("\n".getBytes());
}

return new InputStreamReader(new ByteArrayInputStream(out.toByteArray()));
} catch (Exception e) {
in.close();
fis.close();
this.logger.error("Problem at replaceBackSlashes", e);
}
throw new Exception();
}

最佳答案

不要使用 CSV 解析器来解析 TSV 输入。例如,如果 TSV 包含带引号字符的字段,它将中断。

uniVocity-parsers带有 TSV 解析器。您可以毫无问题地解析十亿行。

解析 TSV 输入的示例:

TsvParserSettings settings = new TsvParserSettings();
TsvParser parser = new TsvParser(settings);

// parses all rows in one go.
List<String[]> allRows = parser.parseAll(new FileReader(yourFile));

如果您的输入太大以至于无法保存在内存中,请执行以下操作:

TsvParserSettings settings = new TsvParserSettings();

// all rows parsed from your input will be sent to this processor
ObjectRowProcessor rowProcessor = new ObjectRowProcessor() {
@Override
public void rowProcessed(Object[] row, ParsingContext context) {
//here is the row. Let's just print it.
System.out.println(Arrays.toString(row));
}
};
// the ObjectRowProcessor supports conversions from String to whatever you need:
// converts values in columns 2 and 5 to BigDecimal
rowProcessor.convertIndexes(Conversions.toBigDecimal()).set(2, 5);

// converts the values in columns "Description" and "Model". Applies trim and to lowercase to the values in these columns.
rowProcessor.convertFields(Conversions.trim(), Conversions.toLowerCase()).set("Description", "Model");

//configures to use the RowProcessor
settings.setRowProcessor(rowProcessor);

TsvParser parser = new TsvParser(settings);
//parses everything. All rows will be pumped into your RowProcessor.
parser.parse(new FileReader(yourFile));

披露:我是这个图书馆的作者。它是开源且免费的(Apache V2.0 许可)。

关于java - 适用于 Java 的优秀且有效的 CSV/TSV 阅读器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13879967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com