Android – 将inputstream存储在文件中

我从一个URL检索XML提要,然后parsing它。 我需要做的也是存储在手机内部,以便当没有互联网连接时,它可以parsing保存的选项,而不是现场的。

我面临的问题是,我可以创buildurl对象,使用getInputStream来获取内容,但它不会让我保存它。

URL url = null; InputStream inputStreamReader = null; XmlPullParser xpp = null; url = new URL("http://*********"); inputStreamReader = getInputStream(url); ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFileAppeal.srl")); //-------------------------------------------------------- //This line is where it is erroring. //-------------------------------------------------------- out.writeObject( inputStreamReader ); //-------------------------------------------------------- out.close(); 

任何想法如何可以去保存inputstream,以便我可以稍后加载。

干杯

在这里,input是你的inputStreamReader 。 然后使用相同的File(name)和FileInputStream将来读取数据。

 try { File file = new File(getCacheDir(), "cacheFileAppeal.srl"); OutputStream output = new FileOutputStream(file); try { byte[] buffer = new byte[4 * 1024]; // or other buffer size int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } output.flush(); } finally { output.close(); } } finally { input.close(); } 

简单的function

尝试这个简单的function整齐地包装在:

 // Copy an InputStream to a File. // private void copyInputStreamToFile(InputStream in, File file) { OutputStream out = null; try { out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while((len=in.read(buf))>0){ out.write(buf,0,len); } } catch (Exception e) { e.printStackTrace(); } finally { // Ensure that the InputStreams are closed even if there's an exception. try { if ( out != null ) { out.close(); } // If you want to close the "in" InputStream yourself then remove this // from here but ensure that you close it yourself eventually. in.close(); } catch ( IOException e ) { e.printStackTrace(); } } } 

感谢Jordan LaPrise和他的回答 。

较短的版本:

 OutputStream out = new FileOutputStream(file); fos.write(IOUtils.read(in)); out.close(); in.close();