Amokrane Chentir
Amokrane Chentir

Reputation: 30385

IOException (Stream is closed) when writing to a file

In order to add some sort of Caching to an Android application, I am trying to write the InputStream that I get from myUrl.openConnection().getInputStream(), to a file.

This is the method that I wrote:

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();
                }
            }
        }
    }

The calling part looks like:

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

I am getting the following exceptions:

(23704): Pas de Notification
W/System.err(24015): java.io.IOException: Stream is closed

What is it, that is closed?

Any ideas?

Thanks!

Upvotes: 1

Views: 4467

Answers (1)

Kaj
Kaj

Reputation: 10949

Looks like the server has sent the data as a compressed stream. Isn't there any code between the line that is opening the stream, and your cache manager?

I would guess that you have some other lines of code that is reading that stream, and that's why it's closed when you get to the cache manager.

Upvotes: 3

Related Questions