当前位置:网站首页>Use kotlin use to simplify file reading and writing
Use kotlin use to simplify file reading and writing
2022-07-25 09:43:00 【Flying time machine】
Use Kotlin USE Simplify file reading and writing
Use Kotlin USE to shorten file reading
Conventional writing
Regular file reading and writing are as follows ;
private val pdfReader by lazy {
val file = File(cacheDir, fileName)
val outputStream = FileOutputStream(file)
try {
val inputStream = assets.open(fileName)
var bytesCopied: Long = 0
val buffer = ByteArray(8 * 1024)
var bytes = inputStream.read(buffer)
while (bytes >= 0) {
outputStream.write(buffer, 0, bytes)
bytesCopied += bytes
bytes = inputStream.read(buffer)
}
} finally {
outputStream.close()
}
PdfReader(file)
}
Use Use
Kotlin1.2 Start , Provide a use Extension method , Can be used in Closeable Class
The above code can be reduced to :
private val pdfReader by lazy {
val file = File(cacheDir, fileName)
val outputStream = FileOutputStream(file)
outputStream.use { outputStream ->
val inputStream = assets.open(fileName)
var bytesCopied: Long = 0
val buffer = ByteArray(8 * 1024)
var bytes = inputStream.read(buffer)
while (bytes >= 0) {
outputStream.write(buffer, 0, bytes)
bytesCopied += bytes
bytes = inputStream.read(buffer)
}
}
PdfReader(file)
}
Benefit time Copy-to
above Stream copy will also have an extension . InputStream.copyTo
private val pdfReader by lazy {
val file = File(cacheDir, fileName)
val outputStream = FileOutputStream(file)
outputStream.use {
fileOut ->
assets.open(fileName).copyTo(fileOut)
}
PdfReader(file)
}
Benefit time 2 outputStream() Expand
File class There is also an extension function outputStream()
private val pdfReader by lazy {
val file = File(cacheDir, fileName)
file.outputStream().use {
fileOut ->
assets.open(fileName).copyTo(fileOut)
}
PdfReader(file)
}
WOW , Transformation completed ,12 Line code , Reduced to 3 That's ok .
Extracurricular reading :
InputStream Read out character string (Text,String)
val myString = inputStream.bufferedReader().use {
bufferReader ->
bufferReader?.readText()
}
边栏推荐
猜你喜欢
随机推荐
cell的定义
STM32+HC05串口蓝牙设计简易的蓝牙音箱
初识Opencv4.X----图像直方图均衡
什么是脑裂问题?
Flutter Rive 多状态例子
Raspberry sect door ban system based on face recognition
Android & Kotlin : 困惑解答
[code source] daily question tree
Definition of cell
Redis installation (Ubuntu)
What is cerebral fissure?
Flutter rive multi state example
一张图讲解 SQL Join 左连 又连
@3-2 optimal threshold of CCF 2020-12-2 final forecast
Flex 布局语法与用例
OC--包装类和处理对象
@4-1 CCF 2020-06-1 linear classifier
*7-2 CCF 2015-09-2 date calculation
Basic network knowledge
main函数的一些操作









