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/