FileOutputStream.write上的ArrayIndexOutOfBoundsException

时间:2018-07-30 17:55:06

标签: android kotlin

我正在使用以下代码从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)

1 个答案:

答案 0 :(得分:2)

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