0

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

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

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

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

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

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

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

4

2 回答 2

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 返回下一个类型字符串。

于 2013-09-04T06:41:50.960 回答
0

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

DataInputStream myDataInputStream=new DataInputStream(myByteInputStream);
myDataInputStream.readDouble();
myDataInputStream.readInt();
myDataInputStream.readChar();
myDataInputStream.readLong();
于 2013-09-04T05:50:16.530 回答