【问题标题】:Read from byte array to console (or file) Java从字节数组读取到控制台(或文件)Java
【发布时间】:2013-09-04 05:20:06
【问题描述】:

所以我有两个文件,一个已读入字节数组的二进制文件,以及一个已读入字符串 ArrayList 的文本文件。现在假设我的 ArrayList 具有值“char”、“int”、“double”,并用作读取我的二进制文件的模式。

这意味着对于字节数组中的前两个字节,我想将其解释为 char,接下来的四个字节为 int,接下来的 8 个字节为 double,这将不断重复,直到文件结束。

我已经实现了对所有数据的读取,但我想不出一个根据模式文件正确解释二进制数据的好方法。有没有好的方法来做到这一点?

IE(伪代码)使用PrintStream out = new PrintStream (new OutputStream(byteArray)) out.writeChar() out.writeInt() out.writeDouble()

Stream 在哪里通过 byteArray 为我工作? (而不是我说 out.writeChar(byteArray[2])?

我已经弄清楚了将架构映射到正确操作的所有逻辑,但是我无法正确转换数据。有什么想法吗?

我想将此信息写入控制台(或文件)。

【问题讨论】:

    标签: java binary buffer bytearray printstream


    【解决方案1】:

    考虑面向对象!您必须为每种所需的数据类型创建一个类,该类能够解析输入流中的数据。

    步骤是(不关心异常):

    1) 为这些类创建一个接口:

    interface DataParser {
        void parse(DataInputStream in, PrintStream out);
    }
    

    2) 为实现该接口的每种数据类型创建一个类。示例:

    class IntParser implements DataParser {
        public void parse(DataInputStream in, PrintStream out) {
            int value = in.readInt();
            out.print(value);
        }
    }
    

    3) 使用 HashMap 注册所有已知解析器及其字符串 ID:

    Map<String, DataParser> parsers = new HashMap<>();
    parsers.put("int", new IntParser());
    

    4) 现在你可以像这样使用它了:

    DataInputStream in = ... ;
    PrintStream out = ... ;
    ...
    while(hasData()) {
        String type = getNextType();
        DataParser parser = parsers.get(type);
        parser.parse(in, out);
    }
    // close streams and work on the output here
    

    方法hasData 应该确定输入流中是否还有数据。 getNextType 方法应该从 ArrayList 返回下一个类型字符串。

    【讨论】:

      【解决方案2】:

      如果你只需要原始类型或字符串,你应该使用 DataInputStream 来包装你的数据:

      DataInputStream myDataInputStream=new DataInputStream(myByteInputStream);
      myDataInputStream.readDouble();
      myDataInputStream.readInt();
      myDataInputStream.readChar();
      myDataInputStream.readLong();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-04
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2011-12-04
        • 2016-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多