package com.flightfeather.obd.common.utils
|
|
import java.io.BufferedWriter
|
import java.io.File
|
import java.io.FileWriter
|
import java.text.SimpleDateFormat
|
import java.util.*
|
|
/**
|
* @author riku
|
* Date: 2019/9/11
|
*/
|
class FileUtil {
|
|
private var file: File
|
private var basePath:String = "${File.separator}ObdData${File.separator}"
|
private var closeThread: Thread? = null
|
private var fw: FileWriter? = null
|
private var bw: BufferedWriter? = null
|
|
init {
|
val fileName = "data-${SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(Date())}.txt"
|
val path = "$basePath$fileName"
|
file = File(path)
|
}
|
|
companion object{
|
var instance: FileUtil? = null
|
get() {
|
if (field == null) {
|
field = FileUtil()
|
}
|
return field
|
}
|
}
|
|
fun saveObdData(str: String) {
|
//检查文档是否存在
|
if (!file.exists()) {
|
file.parentFile.mkdirs()
|
println("----创建文件夹:${file.parentFile.absolutePath}")
|
file.createNewFile()
|
println("----创建文件:${file.absolutePath}")
|
}
|
//文件最大512Kb,超过后新建文档
|
if (file.length() + str.toByteArray().size > 512 * 1024) {
|
val fileName = "data-${SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(Date())}.txt"
|
val path = "$basePath$fileName"
|
file = File(path)
|
file.createNewFile()
|
|
//关闭原有输出流
|
bw?.run {
|
flush()
|
close()
|
}
|
fw?.run {
|
flush()
|
close()
|
}
|
//新建输出流
|
fw = FileWriter(file, true)
|
bw = BufferedWriter(fw)
|
}
|
//第一次写文档时初始化输出流
|
if (bw == null || fw == null) {
|
fw = FileWriter(file, true)
|
bw = BufferedWriter(fw)
|
}
|
|
bw?.run {
|
write(str)
|
newLine()
|
flush()
|
}
|
|
readyToShutDownStream(bw, fw)
|
println("----写入完成")
|
|
}
|
|
private fun readyToShutDownStream(bw: BufferedWriter?, fw:FileWriter?) {
|
//终端上一次的计时线程
|
closeThread?.interrupt()
|
closeThread = Thread(Runnable {
|
//2分钟没有新的数据写入就关闭输出流
|
try {
|
Thread.sleep(20 * 1000)
|
} catch (e: Throwable) {
|
}
|
bw?.run {
|
close()
|
}
|
this.bw = null
|
fw?.run {
|
close()
|
}
|
this.fw = null
|
}).also {
|
it.start()
|
}
|
}
|
}
|