get Bytes from file path via FileInputStream - Android File Input Output

Android examples for File Input Output:InputStream

Description

get Bytes from file path via FileInputStream

Demo Code


//package com.java2s;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;

public class Main {

    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {/*from  w w w  .j ava 2 s. com*/
            File file = new File(filePath);
            if (file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
                byte[] b = new byte[1024];
                int n;
                while ((n = fis.read(b)) != -1) {
                    bos.write(b, 0, n);
                }
                fis.close();
                bos.close();
                buffer = bos.toByteArray();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}

Related Tutorials