在Android Studio Kotlin中读取文本文件并制作指针



我是Android+Kotlin的新手,但我想知道是否有更快的方法来读取文本(.pgn(文件并标记指向文件中位置的指针以供稍后参考。

目前我正在使用RandomAccessFile,但对于一个本应非常快速的进程来说,速度慢得令人难以置信。

这是我目前的代码:

private fun loadPGN() {
try {
val selectedPGN = File((context as MainActivity).filesDir, "mygames.pgn")
val raf = RandomAccessFile(selectedPGN, "r")
val length = raf.length()
raf.seek(0)
charPosition = raf.filePointer
while (charPosition < length) {
val str : String = raf.readLine()
if (str.contains("[Event ")) {
mutableListEvent += charPosition
findMoves = true
}
if (findMoves && ((str.startsWith(str.filter { it.isDigit() }) && !str.startsWith("[")) || str.startsWith("{ "))) {
mutableListMoves += charPosition
findMoves = false
}
charPosition = raf.filePointer
}
for (i in 0 until mutableListEvent.size) {
val event = if (mutableListEvent[i] != mutableListEvent[mutableListEvent.size - 1]) mutableListEvent[i + 1] else length
val moves = mutableListMoves[i]
raf.seek(mutableListEvent[i])
eventStr = raf.readLine().removeRange(0,8).replace(""]", "")
eventMutableList.add(eventStr)
difference += (event - moves)
headerLength += (mutableListMoves[i] - mutableListEvent[i])
raf.seek(moves)
val byteArray = ByteArray(difference[i].toInt())
raf.readFully(byteArray)
val string = String(byteArray)
var stringEdited = String(byteArray).replace("n","")
if (stringEdited.contains("{[")) {
val re = "\{\[.*?]}".toRegex()
stringEdited = re.replace(stringEdited,"")
}
gamePlayMutableList.add(string)
}
// Header Information
for (i in 0 until headerLength.size) {
raf.seek(mutableListEvent[i])
charPosition = raf.filePointer
while (charPosition < mutableListMoves[i]) {
val str = raf.readLine()
if (str.contains("[Site "") || str.contains("[Date "") || str.contains("[Round "") || str.contains("[White "") || str.contains(
"[Black ""
) || str.contains("[Result "") || str.contains("[EventDate "") || str.contains("[PlyCount "")
) {
if (str.contains("[Site "")) {
siteMutableList += str.replace("[Site "", "").replace(""]", "")
}
if (str.contains("[Date "")) {
dateMutableList += str.replace("[Date "", "").replace(""]", "")
}
if (str.contains("[Round "")) {
roundMutableList += str.replace("[Round "", "").replace(""]", "")
}
if (str.contains("[White "")) {
whiteMutableList += str.replace("[White "", "").replace(""]", "")
}
if (str.contains("[Black "")) {
blackMutableList += str.replace("[Black "", "").replace(""]", "")
}
if (str.contains("[Result "")) {
resultMutableList += str.replace("[Result "", "").replace(""]", "")
}
if (str.contains("[EventDate "")) {
eventDateMutableList += str
}
if (str.contains("[PlyCount "")) {
plyCountMutableList += str
}
}
charPosition = raf.filePointer
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
}

一旦我有了指针,我就会将信息加载到回收器视图中,这样你就可以选择你想要的游戏(信息可见(。

我已经对此进行了爬网堆栈溢出,然而大多数问题只是读取整个文本文件并返回,而不是将指针放入引用的位置

所以我设法解决了与此相关的"问题"。raf.readLine()非常慢。这是一个已知的问题,但并没有真正谈论那么多。不管怎样,我现在使用.readFully(),它的速度要快得多。

最新更新