Monday, 15 February 2010

How to read an array of bytes from a file using datainput stream, and print the array of bytes in java -



How to read an array of bytes from a file using datainput stream, and print the array of bytes in java -

i have stored array of bytes byte[] testbyte; testbyte = new byte[]{3,4} file, need read file , assign array of bytes variable , print it.

i have done next code,but not able print array of bytes

public static void main(string[] args) throws ioexception { inputstream = null; datainputstream dis = null; try{ // create input stream file input stream = new fileinputstream("c:\\test.txt"); // create info input stream dis = new datainputstream(is); // count available bytes form input stream int count = is.available(); // create buffer byte[] bs = new byte[count]; // read info buffer dis.read(bs); }

now how store contents in buffer bs array.

please help resolve this

you can store content of bs buffer using new string

public static void main(string[] args) throws ioexception { inputstream = null; datainputstream dis = null; int count = 0; byte[] bs = null; string content = ""; try{ = new fileinputstream("c:\\test.txt"); dis = new datainputstream(is); count = is.available(); bs = new byte[count]; dis.read(bs); // here variable contains buffer content string content = new string(bs); } grab (ioexception e) { } { is.close(); dis.close(); } system.out.println(content); }

edit(answer comment): well, when create new string() instantiate new string byte[] value. but, have array of bytes, can store value of string object on 1 time again using:

bs = content.getbytes();

in advance, don't worry if print of bytes different, [b@199c55a [b@faa824 it's name given object, value same on both.

java arrays datainputstream

No comments:

Post a Comment