【发布时间】:2019-05-28 14:12:30
【问题描述】:
我有一个通用的抽象方法,它获取输入流(可以来自网络套接字,或来自本地存储上的文件)并将数据保存在磁盘上。
下面是函数的小sn-p:
fun saveToFile(data: InputStream, fileDestination: File) {
val bytesWritten = Files.copy(data, fileDestination.toPath(), StandardCopyOption.REPLACE_EXISTING)
println("$bytesWritten bytes were saved at ${fileDestination.absolutePath}")
}
是否可以在过程/方法进行时测量数据保存在磁盘上的速度/速率?例如,是否有可能调用返回速率/速度的函数或更新保存该数据的对象?
如果我自己使用 InputStream/OutputStream 进行实现,我可以有如下示例:
fun saveData(data: InputStream, fileDestination: File, measureSpeed : (Statistics) -> Unit = { }) {
val outputStream = fileDestination.outputStream()
val maxBufferSize = 1024
val totalAmountData = data.available()
var totalBytesWritten = 0
var bytesWriteNextIteration: Int // amount of bytes that will be sent in only one write call
val statistics = Statistics(amountSent = 0, lastWriteBytes = 0, lastWriteTime = 1)
while (totalBytesWritten < totalAmountData) {
bytesWriteNextIteration = totalAmountData - totalBytesWritten
if (bytesWriteNextIteration > maxBufferSize) {
bytesWriteNextIteration = maxBufferSize
}
val bytes = ByteArray(bytesWriteNextIteration)
val nano = measureNanoTime {
outputStream.write(bytes)
}
statistics.amountSent = totalBytesWritten.toLong()
statistics.lastWriteBytes = bytesWriteNextIteration.toLong()
statistics.lastWriteTime = nano
measureSpeed(statistics)
totalBytesWritten += bytesWriteNextIteration
}
outputStream.flush()
outputStream.close()
}
data class Statistics(var amountSent: Long, var lastWriteBytes: Long, var lastWriteTime: Long)
并用measureSpeed方法计算复制/传输率。
【问题讨论】:
-
您的替代 Kotlin 实现远比必要的复杂。在此处查看“标准 Java 复制循环”。它没有你做的 1/4 困难。
-
我在我的实现中使用第一种方法
saveToFile,单行命令有多复杂? @user207421 发布第二个 sn-p 是为了显示我希望通过使用Files.copy方法或类似方法获得的功能。
标签: java performance kotlin stream