[英]Read structured binary file
我想用Java讀取二進制文件。 我知道文件包含一系列數據結構,例如:ANSI ASCII字節字符串,整數,ANSI ASCII字節字符串。 即使我們假設已經知道數據結構的數量(N),如何讀取和獲取文件的數據? 我看到接口DataInput有一個方法readUTF()來讀取字符串,但是它使用UTF-8格式。 我們如何處理ASCII大小寫?
我認為最靈活(最有效)的方法是:
FileInputStream
。 getChannel()
方法獲取FileChannel
。 map()
方法將通道map()
到MappedByteBuffer
。 get*
方法訪問數據。 嘗試
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();
}
我們如何處理ASCII的情況?
您可以使用readFully()處理它。
注意readUTF()適用於由DataOutput.writeUTF()創建的特定格式,我所知道的僅此而已。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.