从二进制文件读取并将某些信息转换为字符串

时间:2012-08-20 08:22:54

标签: java serialization io bytebuffer

我必须从二进制文件中读取数据,如S / W版本,供应商等。 我必须在textarea中显示输出。阅读配置后,usre可以通过串口发送所选文件。 我在这里写了一些代码:

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);
        }
    }

输出

EE��6**UT�h��}�(:�萢Ê�*:�茢���_��(RQ��N���S��h����rMQ��(_Q����9mTT��\�nE�PtP�!E�UtBߌz��z���������

可能有什么问题?

1 个答案:

答案 0 :(得分:2)

您正在将字节转换为字符

所以你必须告诉使用什么编码。如果你没有指出一个InputStreamReader(它是:读取器从输入的字节流读取字符)将使用默认值。我确定默认不是你需要的。

试试这个:

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

作为一般规则:在处理char到bytes的转换时总是指示编码,反之亦然! :)

修改

当然,我假设您的文件已经编码了TEXT。如果它是二进制的,就像@alfasin说的那样......好吧......看垃圾是正常的。您应该读取字节并写入表示它们的字符(例如,作为每个字节的十六进制表示)。