【发布时间】:2014-02-22 16:35:48
【问题描述】:
下载图像后,我的 InputStream 出现了一些问题。 downloadImages 方法返回我在文件中写入的 InputStream。但是 inputStreamToFile 方法中有一个异常:java.io.IOException: BufferedInputStream is closed。代码如下:
下载
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();
}
}
}
}
【问题讨论】:
-
第一种方法关闭HttpConnection时输入流会被关闭。
-
完美,非常感谢!但是...现在我在哪里关闭连接?!
-
最简单的方法是在 downloadImages 中调用 inputStreamToFile,而不是返回 inputStream。另一种解决方案是让一个方法打开 HttpConnection 并返回它,另一个方法关闭 HttpConnection。然后您可以访问这两种方法之间的 InputStream。但是错误处理可能有点混乱。
标签: android inputstream ioexception