mirror of
https://github.com/gedoor/legado.git
synced 2024-09-01 09:34:25 +08:00
优化
This commit is contained in:
parent
45408b7cc2
commit
4f465fcb69
@ -1,6 +1,7 @@
|
||||
package io.legado.app.ui.main.bookshelf
|
||||
|
||||
import android.app.Application
|
||||
import com.google.gson.stream.JsonWriter
|
||||
import io.legado.app.R
|
||||
import io.legado.app.base.BaseViewModel
|
||||
import io.legado.app.data.appDb
|
||||
@ -14,6 +15,9 @@ import io.legado.app.model.webBook.WebBook
|
||||
import io.legado.app.utils.*
|
||||
import kotlinx.coroutines.Dispatchers.IO
|
||||
import kotlinx.coroutines.isActive
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.OutputStreamWriter
|
||||
|
||||
class BookshelfViewModel(application: Application) : BaseViewModel(application) {
|
||||
|
||||
@ -66,19 +70,33 @@ class BookshelfViewModel(application: Application) : BaseViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
fun exportBookshelf(books: List<Book>?, success: (json: String) -> Unit) {
|
||||
fun exportBookshelf(books: List<Book>?, success: (file: File) -> Unit) {
|
||||
execute {
|
||||
val exportList = arrayListOf<Map<String, String?>>()
|
||||
books?.forEach {
|
||||
books?.let {
|
||||
val path = "${context.filesDir}/books.json"
|
||||
FileUtils.delete(path)
|
||||
val file = FileUtils.createFileWithReplace(path)
|
||||
@Suppress("BlockingMethodInNonBlockingContext")
|
||||
FileOutputStream(file).use { out ->
|
||||
val writer = JsonWriter(OutputStreamWriter(out, "UTF-8"))
|
||||
writer.setIndent(" ")
|
||||
writer.beginArray()
|
||||
books.forEach {
|
||||
val bookMap = hashMapOf<String, String?>()
|
||||
bookMap["name"] = it.name
|
||||
bookMap["author"] = it.author
|
||||
bookMap["intro"] = it.getDisplayIntro()
|
||||
exportList.add(bookMap)
|
||||
GSON.toJson(bookMap, bookMap::class.java, writer)
|
||||
}
|
||||
GSON.toJson(exportList)
|
||||
writer.endArray()
|
||||
writer.close()
|
||||
}
|
||||
file
|
||||
} ?: throw NoStackTraceException("书籍不能为空")
|
||||
}.onSuccess {
|
||||
success(it)
|
||||
}.onError {
|
||||
context.toastOnUi("导出书籍出错\n${it.localizedMessage}")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -49,12 +49,12 @@ fun Gson.writeToOutputStream(out: OutputStream, any: Any) {
|
||||
writer.beginArray()
|
||||
any.forEach {
|
||||
it?.let {
|
||||
GSON.toJson(it, it::class.java, writer)
|
||||
toJson(it, it::class.java, writer)
|
||||
}
|
||||
}
|
||||
writer.endArray()
|
||||
} else {
|
||||
GSON.toJson(any, any::class.java, writer)
|
||||
toJson(any, any::class.java, writer)
|
||||
}
|
||||
writer.close()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user