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
一直以来。任何想法都错了吗?
答案 0 :(得分:2)
基于TypedInput的这个javadoc:
将字节读取为流。除非另有说明,否则此方法可以 只被叫一次。打电话的责任是关闭 流。
我猜想每次调用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();
}
}