Tuesday, March 8, 2011

How to read a file in bytes - Android

private static final int BUFFER_SIZE = 0x1000; // 4K

FileInputStream fin;

try {
fin = new FileInputStream(directory);
BufferedInputStream bis = new BufferedInputStream(fin);
DataInputStream dis = new DataInputStream(bis);
byte fileContent[] = toByteArray(dis);
}
catch(Exception e)
{
}

public static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out);
return out.toByteArray();
}


public static long copy(InputStream from, OutputStream to) throws IOException {
byte[] buf = new byte[BUFFER_SIZE];
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}

4 comments: