Skip to content Skip to sidebar Skip to footer

Reading Binary File From Sdcard Using Stream Classes In Android

Can anybody have any idea how to read a binary file which resides in sdcard using Streams, like Inputstream, CountingInputStream or SwappedDataInputStream? I am using these three s

Solution 1:

This is a simple method that just copies the content of an input stream to an output stream:

/**
     * Copy the content of the input stream into the output stream, using a
     * temporary byte array buffer whose size is defined by
     * {@link #IO_BUFFER_SIZE}.
     * 
     * @param in
     *            The input stream to copy from.
     * @param out
     *            The output stream to copy to.
     * 
     * @throws java.io.IOException
     *             If any error occurs during the copy.
     */publicstaticvoidcopy(InputStream in, OutputStream out)throws IOException {
            byte[] b = newbyte[IO_BUFFER_SIZE];
            int read;
            while ((read = in.read(b)) != -1) {
                    out.write(b, 0, read);
            }
    }

It's taken from an app that I made a while ago: http://code.google.com/p/meneameandroid/source/browse/trunk/src/com/dcg/util/IOUtilities.java

And to make sure the dir exists where you want to write/read your data I used something like this:

/**
     * Prepares the SDCard with all we need
     */privatevoidprepareSDCard() {
        // Create app dir in SDCard if possible
        File path = new File("/sdcard/MyAppDirectory/");
        if(! path.isDirectory()) {
            if ( path.mkdirs() )
            {
                Log.d(TAG,"Directory created: /sdcard/MyAppDirectory");
            }
            else
            {
                Log.w(TAG,"Failed to create directory: /sdcard/MyAppDirectory");
            }
        }
    }

The permission to write/read from the SD card is:

<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Edited: Linkes updated

Post a Comment for "Reading Binary File From Sdcard Using Stream Classes In Android"