我有一个 Java 服务器应用程序可以下载 CSV 文件并对其进行解析。解析可能需要 5 到 45 分钟,每小时发生一次。这种方法是应用程序的瓶颈,因此它不是过早的优化。到目前为止的代码:
client.executeMethod(method);
InputStream in = method.getResponseBodyAsStream(); // this is http stream
String line;
String[] record;
reader = new BufferedReader(new InputStreamReader(in), 65536);
try {
// read the header line
line = reader.readLine();
// some code
while ((line = reader.readLine()) != null) {
// more code
line = line.replaceAll("\"\"", "\"NULL\"");
// Now remove all of the quotes
line = line.replaceAll("\"", "");
if (!line.startsWith("ERROR"){
//bla bla
continue;
}
record = line.split(",");
//more error handling
// build the object and put it in HashMap
}
//exceptions handling, closing connection and reader
是否有任何现有的库可以帮助我加快速度?我可以改进现有代码吗?
最佳答案
Apache Commons CSV
你见过Apache Commons CSV吗? ?
注意使用split
请记住,split
仅返回数据 View ,这意味着原始 line
对象不符合垃圾回收条件,而存在对任何对象的引用其意见。也许制作防御性副本会有所帮助? ( Java bug report )
它在对包含逗号的转义 CSV 列进行分组时也不可靠
关于java - 快速 CSV 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6857248/