Android,从输入流创建文件在 while 循环内挂起

Android, create file from input stream hangs inside while loop

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();
        }
    }