android - FileOutputStream.write 上的 ArrayIndexOutOfBoundsException
问题描述
我正在使用以下代码从 URL 下载图像并将其保存到 sd 卡。虽然图像下载得很好,但应用程序崩溃了。问题出在哪里?
val picUrl = URL("http://example.com/")
val urlConnection = picUrl.openConnection() as HttpURLConnection
urlConnection.requestMethod = "GET"
urlConnection.doOutput = true
urlConnection.connect()
val path = File(Environment.getExternalStorageDirectory().toString() + "/myFolder")
if (!path.exists()){
path.mkdirs()
}
val file = File(path,((Calendar.getInstance().getTimeInMillis()).toString() + ".jpg"))
file.createNewFile()
val fileOutput = FileOutputStream(file)
val inputStream = urlConnection.inputStream
val totalSize = urlConnection.contentLength
var downloadedSize = 0
val buffer = ByteArray(1024)
var bufferLength: Int
do {
bufferLength = inputStream.read(buffer)
if (bufferLength == 0)
break
fileOutput.write(buffer,0,bufferLength)
downloadedSize += bufferLength
}
while (true)
fileOutput.close()
if (totalSize == downloadedSize){
//the image has been downloaded
//do sth with downloaded image
}
logcat中的错误:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1024; regionStart=0; regionLength=-1
at java.util.Arrays.checkOffsetAndCount(Arrays.java:1719)
at libcore.io.IoBridge.write(IoBridge.java:487)
at java.io.FileOutputStream.write(FileOutputStream.java:186)
解决方案
没有更多数据时返回更改if (bufferLength == 0)
为-1if (bufferLength == -1)
推荐阅读
- angular - 角反应形式检查现有数字
- typescript - 打字稿:从内部函数访问对象的属性
- javascript - 我需要解析由对象内部数组组成的json数组
- python - 用样本均值计算均方误差
- google-calendar-api - 在 24 小时内插入约 100 个事件(有与会者)时,超出了 Google 日历的使用限制
- ruby-on-rails - 用于 action_cable 的 Kubernetes websocket 探针
- javascript - NestJs 在 @Cron 装饰器上使用环境配置
- css - 将 Metronic 与 Laravel 8 集成 - Webmix 失败
- javascript - React Router - 将“参数”从具有它们的路径传递到没有它们的路径
- php - 使用 $_GET 从 HTML 中获取选择选项值