From d78f7596381e089f2f19c388b30ff2466201c8d1 Mon Sep 17 00:00:00 2001 From: kunfei Date: Fri, 16 Aug 2019 14:24:43 +0800 Subject: [PATCH] up --- .../main/java/io/legado/app/help/BookHelp.kt | 36 +++++++++++++++++++ .../main/java/io/legado/app/help/FileHelp.kt | 35 ++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 app/src/main/java/io/legado/app/help/FileHelp.kt diff --git a/app/src/main/java/io/legado/app/help/BookHelp.kt b/app/src/main/java/io/legado/app/help/BookHelp.kt index fa42f9cfe..965096352 100644 --- a/app/src/main/java/io/legado/app/help/BookHelp.kt +++ b/app/src/main/java/io/legado/app/help/BookHelp.kt @@ -1,11 +1,35 @@ package io.legado.app.help +import io.legado.app.App import io.legado.app.data.entities.Book import io.legado.app.data.entities.BookChapter +import io.legado.app.utils.getPrefString +import java.io.BufferedWriter +import java.io.File +import java.io.FileWriter +import java.io.IOException object BookHelp { + var downloadPath = App.INSTANCE.getPrefString("downloadPath") ?: App.INSTANCE.getExternalFilesDir(null) + fun saveContent(book: Book, bookChapter: BookChapter, content: String) { + if (content.isEmpty()) { + return + } + val filePath = getChapterPath(book, bookChapter) + val file = FileHelp.getFile(filePath) + //获取流并存储 + try { + BufferedWriter(FileWriter(file)).use { writer -> + writer.write(bookChapter.title + "\n\n") + writer.write(content) + writer.write("\n\n") + writer.flush() + } + } catch (e: IOException) { + e.printStackTrace() + } } @@ -21,6 +45,18 @@ object BookHelp { return null } + private fun getChapterPath(book: Book, bookChapter: BookChapter): String { + val bookFolder = formatFolderName(book.name + book.bookUrl) + val chapterFile = String.format("%05d-%s", bookChapter.index, formatFolderName(bookChapter.title)) + return "$downloadPath${File.separator}book_cache${File.separator}$bookFolder${File.separator}$chapterFile.nb" + } + + private fun formatFolderName(folderName: String): String { + return folderName.replace("/", "") + .replace(":", "") + .replace(".", "") + } + fun formatAuthor(author: String?): String { return author ?.replace("作\\s*者[\\s::]*".toRegex(), "") diff --git a/app/src/main/java/io/legado/app/help/FileHelp.kt b/app/src/main/java/io/legado/app/help/FileHelp.kt new file mode 100644 index 000000000..123f31172 --- /dev/null +++ b/app/src/main/java/io/legado/app/help/FileHelp.kt @@ -0,0 +1,35 @@ +package io.legado.app.help + +import java.io.File +import java.io.IOException + +object FileHelp { + + + //获取文件夹 + fun getFolder(filePath: String): File { + val file = File(filePath) + //如果文件夹不存在,就创建它 + if (!file.exists()) { + file.mkdirs() + } + return file + } + + //获取文件 + @Synchronized + fun getFile(filePath: String): File { + val file = File(filePath) + try { + if (!file.exists()) { + //创建父类文件夹 + getFolder(file.parent) + //创建文件 + file.createNewFile() + } + } catch (e: IOException) { + } + + return file + } +} \ No newline at end of file