如何使用Kotlin提高文件(.CSV,.TXT)的读取效率



我用Kotlin在JavaFX中制作了一个程序,我设法用"分隔CSV和TXT读数"我有效率问题,我不知道如何提高SQL查询构建的效率。

fun generatedDelimited(filePath: String, table: String = "") {
val sourceFile = File(filePath)
var line: String?
var header: Array<String>? = null
val lines: MutableList<List<String>> = ArrayList()
try {
BufferedReader(FileReader(sourceFile)).use { br ->
header = br.readLine().split(";").toTypedArray();
while (br.readLine().also { line = it } != null) {
val values : Array<String> = line!!.split(";").toTypedArray();
lines.add(Arrays.asList(*values))
}
}
} catch (e: IOException) {
e.printStackTrace()
}
val joined = "INSERT INTO $table  (${header!!.joinToString(separator = ",")})n"
var textSelect = "${joined}SELECT * FROM ( n"
var selectUnion = ""
var lineNo = 1
for (line in lines) {
var columnNo = 0
var comma = ", "
var select = "SELECT "
var union = "UNION ALLn"
if (lines.size.equals(lineNo)) {
union = ""
}
for (value in line) {
if (columnNo ==  1) {
select = ""
}
if (line.size.equals(columnNo+1)) {
comma = " FROM DUAL n$union"
}
selectUnion += "$select'$value' as ${header!![columnNo]}$comma"
columnNo++
}
lineNo++
}
textSelect += "$selectUnion);"
querySQL.text = textSelect
}

结果:

INSERT INTO werwsf  (DATA1,DATA2,DATA3,DATA4,DATA5)
SELECT * FROM ( 
SELECT 'HOLA1' as DATA1, 'HAKA2' as DATA2, 'HAD3' as DATA3, '' as DATA4, 'ASDAD5' as DATA5 FROM DUAL 
UNION ALL
SELECT 'HOLA6' as DATA1, 'HAKA7' as DATA2, 'HAD8' as DATA3, 'FA9' as DATA4, 'ASDAD10' as DATA5 FROM DUAL 
);

有办法提高效率吗1600行需要5分钟

谢谢。

这应该是代码的优化版本:

我使用了kotlin标准的joinToString函数,它像@0009laH建议的那样在后台使用StringBuilder。我还删除了冗余列表&lt-&gt;数组转换并替换了拆分,然后用替换函数连接回第一行(头(,因为它与原始代码中的效果相同,而且速度更快。所有这些变化都应该导致更快、更可读、更简洁的代码

fun generatedDelimited(filePath: String, table: String = "") {
val sourceFile = File(filePath)
val fileLines: List<String> = sourceFile.readLines()
val header: String = fileLines.first().replace(';', ',')
val lines: List<List<String>> = fileLines.drop(1).map { line ->
line.split(";")
}
val selectUnion = lines.joinToString(separator = "UNION ALLn") { line ->
line.withIndex().joinToString(separator = ", ", prefix = "SELECT", postfix = " FROM DUALn") { (columnNo, value) ->
"'$value' as ${header[columnNo]}"
}
}
querySQL.text = "INSERT INTO $table  ($header)nSELECT * FROM ( n$selectUnion);"
}

相关内容

  • 没有找到相关文章

最新更新