0

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?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
lazyprogrammer
  • 633
  • 9
  • 26
  • It looks like a binary file alright... :) – Nir Alfasi Aug 20 '12 at 08:24
  • @martijno is right. You don't need an intermediate `DataInputStream`. Its purpose is reading atomic data (as integer, String, Date, etc). It seems you only need FileInputStream (read bytes from file) +InputStreamReader (read chars from bytes). – helios Aug 20 '12 at 10:03
  • The only thing you could use is a BufferedInputStream (instead of DataInputStream). It provides the same InputStream but it reads big chunks of data and buffer it, to avoid asking 4 bytes each time a lot of times. I mean: it optimizes reading while you use it normally. – helios Aug 20 '12 at 10:05

1 Answers1

2

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:

new InputStreamReader(in, "UTF-8"); // or whatever encoding you need

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).

helios
  • 13,574
  • 2
  • 45
  • 55