首页 > 解决方案 > 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)

标签: androidkotlin

解决方案


没有更多数据时返回更改if (bufferLength == 0)
为-1if (bufferLength == -1)


推荐阅读