I have to read data from a binary file like S/W version,vendor etc.
i have to show the output in a textarea.After reading the configurations the usre can send the selected file through a serial port.
I have written some code here:
InputStream is=null;
try {
File urt=filebrowser.getSelectedFile();
is = new FileInputStream(urt);
DataInputStream in = new DataInputStream(is);
long l=urt.length();
char[] bytes= new char[(int)l];
int o=bytes.length;
errlabel.setText(String.valueOf(o));
String content;
int offset;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int numRead;
try {
br.read(bytes, 0, 46);
while ((content = br.readLine()) != null) {
StringBuilder sb=new StringBuilder(content);
jTextArea1.setText(sb.toString());
errlabel.setText(""+sb.length());
}
} catch (IOException ex) {
Logger.getLogger(MyBoxUpdator.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MyBoxUpdator.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
is.close();
} catch (IOException ex) {
Logger.getLogger(MyBoxUpdator.class.getName()).log(Level.SEVERE, null, ex);
}
}
And The Output
EE��6**UT�h��}�(:�萢Ê�*:�茢���_��(RQ��N���S��h����rMQ��(_Q����9mTT��\�nE�PtP�!E�UtBߌz��z���������
What may be wrong?
You are converting bytes into chars
So you must tell what encoding to use. If you don’t indicate one the InputStreamReader (it is: reader that reads chars from an input stream of bytes) will use a default. I’m sure the default is not what you need.
Try this:
As a general rule: always indicate encoding when dealing with char to bytes conversion and viceversa! 🙂
Edit
Of course, I’m assuming your file has TEXT encoded into it. If it’s binary as @alfasin said… well… it’s normal to see garbage. You should read bytes and write chars representing them (as an hex representation of each byte, by example).