gpt4 book ai didi

android - FileOutputStream.write 上的 ArrayIndexOutOfBoundsException

转载 作者:太空狗 更新时间:2023-10-29 13:03:44 25 4
gpt4 key购买 nike

我正在使用以下代码从 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)
if (bufferLength == -1)
没有更多数据时返回-1

关于android - FileOutputStream.write 上的 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51599717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com