2013-04-17 206 views
0

我想用Java读取二进制文件。我知道该文件包含一系列数据结构,如:ANSI ASCII字节字符串,Integer,ANSI ASCII字节字符串。即使假设数据结构的数量已知(N),我如何读取和获取文件的数据?我看到接口DataInput有一个读取字符串的方法readUTF(),但它使用UTF-8格式。我们如何处理ASCII码的情况?阅读结构化二进制文件

回答

0

最灵活(高效的)的做法,我认为是:

  1. 打开FileInputStream
  2. 使用流的getChannel()方法获取FileChannel
  3. 使用频道的map()方法将频道映射到MappedByteBuffer
  4. 通过缓冲区的各种get*方法访问数据。
0

尝试

public static void main(String[] args) throws Exception { 
    int n = 10; 
    InputStream is = new FileInputStream("bin"); 
    for (int i = 0; i < n; i++) { 
     String s1 = readAscii(is); 
     int i1 = readInt(is); 
     String s2 = readAscii(is); 
    } 
} 

static String readAscii(InputStream is) throws IOException, EOFException, 
     UnsupportedEncodingException { 
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    for (int b; (b = is.read()) != 0;) { 
     if (b == -1) { 
      throw new EOFException(); 
     } 
     out.write(b); 
    } 
    return new String(out.toByteArray(), "ASCII"); 
} 

static int readInt(InputStream is) throws IOException { 
    byte[] buf = new byte[4]; 
    int n = is.read(buf); 
    if (n < 4) { 
     throw new EOFException(); 
    } 
    ByteBuffer bbf = ByteBuffer.wrap(buf); 
    bbf.order(ByteOrder.LITTLE_ENDIAN); 
    return bbf.getInt(); 
} 
+0

单纯的代码不是答案。你必须解释它,并解释它是如何回答这个问题的。 – EJP

0

我们如何处理ASCII的情况下?

你可以用readFully()来处理它。

NB readUTF()用于由DataOutput.writeUTF()创建的特定格式,以及我没有意识到的其他任何内容。