gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:56:48 25 4
gpt4 key购买 nike

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/

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