写入文件时IOException(Stream已关闭)

时间:2011-06-08 13:08:04

标签: java android inputstream ioexception

为了向Android应用程序添加某种缓存,我尝试将InputStream的{​​{1}}写入文件。

这是我写的方法:

myUrl.openConnection().getInputStream()

调用部分如下:

public static void saveInputStream(InputStream inputStream) throws IOException, Exception {
        FileOutputStream out = null;
        OutputStream os = null;

        try {
            String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
            String fileName = "feedData.txt";
            File myFile = new File(baseDir + File.separator + fileName);

            out = new FileOutputStream(myFile, false);
            os = new BufferedOutputStream(out);

            byte[] buffer = new byte[65536];
            int byteRead = 0;

            while ((byteRead = inputStream.read(buffer)) != -1) {
                Log.d("CacheManager", "Reading.......");
                os.write(buffer, 0, byteRead);
            }
        } catch(IOException e) {
            e.printStackTrace();
            throw new IOException();
        } catch(Exception e) {
            throw new Exception();
        } finally {
            if (out != null) {
                try {   
                    out.close();
                } catch (IOException e) {
                    throw new IOException();
                }
            }
        }
    }

我收到以下例外情况:

URL feedUrl = new URL("rss_feed_url");
InputStream inputStream = feedUrl.openConnection().getInputSream();
CacheManager.saveInputSteam(inputStream);

这是什么,关闭了?

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

看起来服务器已将数据作为压缩流发送。在打开流的行和缓存管理器之间是不是有任何代码?

我猜你还有一些其他代码行正在读取该流,这就是为什么当你到达缓存管理器时它被关闭了。

答案 1 :(得分:-1)

首先,我会使用BufferedReader来读取流。这样你就可以使用while((input = reader.read())!= null)来循环。

但是,您的问题可能与您正在传递的InputStream有关。您提供的代码最像是对您的例外不负责任!那么你在哪里以及如何创建这个InputStream?

相关问题