Masalah

Sebelumnya saya sudah share tentang cara menulis bytes ke dalam file pada pemrograman Blackberry. Kali ini saya sharing juga cara membaca isi file dari file sistem (memori device atau media card), bukan dari resource project. Tentang membaca isi file di dalam resource project, sudah pernah saya bahas di post sebelumnya.

Jika Anda membaca tulisan saya tentang bagaimana menulis ke dalam file, maka Anda akan pahami, masalah yang mungkin timbul ketika membaca isi file masih sama, yaitu masalah path. Maka pemecahannya pun kurang lebih sama, yaitu dengan melengkapi path file-nya.

Solusi

Berikut ini contoh kode program yang saya tulis.

   /**
* Method to get all bytes from a file.
*
* @param path
* @return
* @throws IOException
*/
    public static byte[] getFileContent(String path) throws IOException {
        FileConnection file = null;
 
        if (path.startsWith("file://"))
            path = path.substring(7);
        else if (!path.startsWith("/"))
            path = "/" + path;
 
        try {
            file = (FileConnection) Connector.open("file://" + path,
                    Connector.READ);
            int fileSize = (int) file.fileSize();
            if (fileSize > 0) {
                byte[] data = new byte[fileSize];
                InputStream input = file.openInputStream();
                input.read(data);
                Thread.yield();
                input.close();
                return data;
            } else {
                throw new NullPointerException("File " + path + " is empty.");
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (file != null && file.isOpen())
                file.close();
        }
    }

Mudah-mudahan bermanfaat.

September 27, 2011

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Mobile and Web Analytics