Android:IOException BufferedInputStream在下载后关闭
下载图像后,InputStream出现一些问题。downloadImages方法返回我在文件中写入的InputStream。但是inputStreamToFile方法中有一个异常:java.io.IOException:BufferedInputStream已关闭。代码如下: 下载Android:IOException BufferedInputStream在下载后关闭,android,inputstream,ioexception,Android,Inputstream,Ioexception,下载图像后,InputStream出现一些问题。downloadImages方法返回我在文件中写入的InputStream。但是inputStreamToFile方法中有一个异常:java.io.IOException:BufferedInputStream已关闭。代码如下: 下载 public static InputStream downloadImages(String imageUrl) { HttpURLConnection httpConn = null;
public static InputStream downloadImages(String imageUrl) {
HttpURLConnection httpConn = null;
String urlBase = imageUrl;
if(D) Log.d(TAG, "downloadImages(): url request: " + urlBase);
try {
URL url = new URL(urlBase);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(SystemConstants.TIMEOUT_CONNECTION);
httpConn.setReadTimeout(SystemConstants.SOCKET_CONNECTION);
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
return inputStream;
}
} catch (IOException e) {
Log.w(TAG, "downloadImages(): exception: " + e);
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(httpConn != null) httpConn.disconnect();
}
return null;
}
从IS到文件
public static void inputStreamToFile(InputStream is) {
if(D) Log.d(TAG, "inputStreamToFile() called");
OutputStream outputStream = null;
try {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!Utils.isExternalStorageRemovable() ?
Utils.getExternalCacheDir(App.getContext()).getPath() :
App.getContext().getCacheDir().getPath();
// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File(cachePath + File.separator + "vr"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
if(D) Log.d(TAG, "read called");
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
if(D) Log.d(TAG, "inputStreamToFile(): outputStream is not null");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
放入日志。然后只有我们才能识别错误、bug等当您使用第一种方法关闭HttpConnection时,inputstream将被关闭。太好了,非常感谢!但是现在我在哪里关闭连接?!最简单的方法是在下载图像内部调用inputStreamToFile,而不是返回inputStream。另一种解决方案是使用一种方法打开HttpConnection并返回它,另一种方法关闭HttpConnection。然后可以在这两个方法之间访问InputStream。但是错误处理可能有点混乱。