Android - Store inputstream in file

前端 未结 7 2043
[愿得一人]
[愿得一人] 2020-12-02 11:56

I am retrieveing an XML feed from a url and then parsing it. What I need to do is also store that internally to the phone so that when there is no internet connection it can

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 12:29

    Simple Function

    Try this simple function to neatly wrap it up in:

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

    Thanks to Jordan LaPrise and his answer.

提交回复
热议问题