Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

How to Read a File as Byte Array?

$
0
0

Read file as byte array in JavaIn order to get the contents of the file as array of bytes we use BufferedInputStream on top of FileInputStream. Once the file handle is open, we read the bytes from the file in chunks and copy the byte chunks in the buffer using the System.arraycopy.<!--break-->

The Snippet

package com.livrona.snippets.io;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import com.livrona.snippets.util.Log;

/**
* A simple snippet that read a file as an byte array.
*
* @author java4learners
*/

publicclass FileToArray {

privatestatic Log log =new Log(FileToArray.class);

/**
* Reads a file storing intermediate data into an array.
*
* @param file
* the file to be read
* @return a file data
*/

publicstaticbyte[] read2array(String file) throws Exception {
Exception ex =null;
InputStream in =null;
byte[] out =newbyte[0];

try {
in =new BufferedInputStream(new FileInputStream(file));

// the length of a buffer can vary
int bufLen =20000 * 1024;
byte[] buf =newbyte[bufLen];
byte[] tmp =null;
int len =0;

while ((len = in.read(buf, 0, bufLen)) != -1) {
// extend array
tmp =newbyte[out.length + len];

// copy data
System.arraycopy(out, 0, tmp, 0, out.length);
System.arraycopy(buf, 0, tmp, out.length, len);
out = tmp;
tmp =null;
}
} catch (Exception e) {
ex = e;
} finally {
// always close the stream
if (in !=null) {
try {
in.close();
} catch (Exception e) {
}
}

if (ex !=null) {
throw ex;
}
}

return out;
}

/**
* Test method
*
* @param args
*/

publicstaticvoid main(String[] args) {

if (args.length !=1) {
System.out
.println("Usage: java com.livrona.snippets.io.FileArray <Path file>");
System.exit(0);
}

try {
log.debug("About to Read file : "+ args[0]);
byte[] contents = FileToArray.read2array(args[0]);
log.info("File Size : "+ contents.length);
} catch (Exception e) {
log.error("Failed to read file : "+ e.getMessage(), e);
}
}
}



The Ouput

Example, read the content of an image file, and display the size.

java com.livrona.snippets.io.FileToArray C:\images\IMG_0002.jpg

DEBUG>[FileToArray]-About to Read file : C:\images\IMG_0002.jpg
INFO>[FileToArray]-File Size : 1242702


Viewing all articles
Browse latest Browse all 178

Trending Articles