读取InputStream时出现IllegalStateException

时间:2017-11-13 12:55:53

标签: android inputstream illegalstateexception

我在Android应用中使用此功能从网址下载文件:

public static boolean downloadFile(URL url, File file) throws IOException {

    if(!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        return false;
    }

    File temp = File.createTempFile("file_", ".temp", file.getParentFile());
    temp.deleteOnExit();

    InputStream input = url.openStream();
    try {

        OutputStream output = new FileOutputStream(temp);

        try {
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, bytesRead); }
        }
        finally { output.close(); }
    }
    finally { input.close(); }

    return temp.renameTo(file);
}

我收到一些报告IllegalStateException的崩溃报告,正如您在此堆栈跟踪中看到的那样:

  

java.lang.IllegalStateException:已关闭       在com.android.okhttp.okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:174)       在com.android.okhttp.internal.http.HttpEngine $ 2.read(HttpEngine.java:1212)       在com.android.okhttp.okio.RealBufferedSource $ 1.read(RealBufferedSource.java:396)       在com.egosventures.stable360.core.utils.Utils.downloadFile(Utils.java:257)

我的代码中有什么值得担心的,或者只是因为我的用户丢失了他的互联网访问权限而发生此异常(我想知道是否捕获异常并且优雅地失败是我能做的最好的事情)?

0 个答案:

没有答案