java - Android,从输入流创建文件卡在while循环内

标签 java android retrofit fileoutputstream

try {

    Log.d("TEST", "start converting...");

    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "out.pdf");
    file.createNewFile();
    OutputStream out = new FileOutputStream(file);

    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = resp.getBody().in().read(bytes)) != -1) {
        out.write(bytes, 0, read);
        Log.d("TEST", "looping");
    }

    Log.d("TEST", "finish converting");

} catch (IOException e) {
    e.printStackTrace();
}

上面的代码应该从输入流创建一个 pdf 文件。然而它被困在 while 循环内。它打印

looping

一直以来。任何想法有什么问题吗?

最佳答案

基于此 TypedInput 的 javadoc:

Read bytes as stream. Unless otherwise specified, this method may only be called once. It is the responsibility of the caller to close the stream.

我猜测调用 in() 每次都会创建一个新的 InputStream。因此,您永远不会跳出 while 循环,因为每次都会有一个新的 InputStream。

相反,只需像这样调用 in() 一次,看看是否可以解决问题:

    InputStream in = null;

    try {

        Log.d("TEST", "start converting...");

        File file = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                "out.pdf");
        file.createNewFile();
        OutputStream out = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

         in = resp.getBody().in();

        while ((read = in.read(bytes)) != -1) {
            out.write(bytes, 0, read);
            Log.d("TEST", "looping");
        }

        Log.d("TEST", "finish converting");

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
             in.close();
        }
    }

关于java - Android,从输入流创建文件卡在while循环内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28462584/

相关文章:

java - 兴趣点 : not iterating through all excel row while inserting values to database

java - 我为 Java Spring 使用哪个主类?

android - ffmpeg 规模过滤器耗时太长

android - Retrofit 中是否有钩子(Hook)来获取最后的请求详细信息?

java - 使用改造 2 分段上传失败

java - 如何在 JSF Web 应用程序中播放声音?

android - TextView 动画 - 淡入、等待、淡出

android - Groovy调用adb命令来提取文件,但是新文件不可见

android - Retrofit 是否支持 json 解析或类似的键路径?

java - Excel 中的空单元格返回 Null(Java、POI)