2011-06-08 73 views
1

为了向Android应用程序添加某种缓存,我试图将InputStream(我从myUrl.openConnection().getInputStream()获得)写入文件。写入文件时发生IOException(流关闭)

这是我写的方法:

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

我收到以下情况除外:

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

这是什么,那是封闭的?

任何想法?

谢谢!

回答

3

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

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

+0

的确,你猜对了!谢谢,问题解决了! – 2011-06-08 13:41:02

-1

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

但是,您的问题可能与您通过的InputStream有关。你提供的这段代码是最不喜欢你的例外的!那么你在哪里以及如何创建这个InputStream?

+2

“Reader”与“InputStream”不同的用例不同:它只有**在阅读文本数据(实际上关心文本数据)时才有意义。这里情况不同。 – 2011-06-08 13:20:41

+0

什么?那不是真的!你可以做新的BufferedReader(新的InputStream(bla))! BufferedReader可以读取所有内容,并且比使用read(buffer)读取流的速度更快,更快。 – 2011-06-08 13:23:08

+0

不,@Vincent,你错了:['BufferedReader']的唯一构造函数(http://download.oracle.com /javase/6/docs/api/java/io/BufferedReader.html)带有其他'Reader'实例,所以你不能传入'InputStream'。也许你正在考虑一个'BufferedInputStream'? – 2011-06-08 13:25:46

相关问题