丹陽市制作網(wǎng)站南昌網(wǎng)站建設(shè)
基于Java實(shí)現(xiàn)DBase DBF文件的解析和顯示
JDK19編譯運(yùn)行,實(shí)現(xiàn)了數(shù)據(jù)庫字段和數(shù)據(jù)解析顯示。
首先解析數(shù)據(jù)庫文件頭代碼
byte bytes[] = Files.readAllBytes(Paths.get(file));BinaryBufferArray bis = new BinaryBufferArray(bytes);DBF dbf = new DBF();dbf.VersionNumber = bis.ReadUInt8(); // 版本號dbf.DateOfLastUpdate = bis.ReadBytes(3); // 最后更新日期dbf.NumberOfRecords = bis.ReadUInt32(); // 記錄數(shù)量dbf.LengthOfHeaderStructure = bis.ReadUInt16(); // 文件頭長(內(nèi)容開始位置)dbf.LengthOfEachRecord = bis.ReadUInt16(); // 每條記錄長度short Reserved = bis.ReadInt16();dbf.IncompleteTransac = bis.ReadUInt8(); dbf.EncryptionFlag = bis.ReadUInt8();dbf.FreeRecordThread = bis.ReadInt32();long ReservedForMultiUser= bis.ReadInt64();dbf.MDXFlag = bis.ReadUInt8();dbf.LanguageDriver = bis.ReadUInt8(); Reserved = bis.ReadInt16();
解析字段代碼
dbf.fields = new Vector<Field>();while (true) {byte _b = bis.ReadInt8();if (_b == 0x0d) // 是否結(jié)束break ;byte[] bs = bis.ReadInt8(31);byte[] all = new byte[32];all[0] = _b;System.arraycopy(bs, 0, all, 1, 31);Field field = Field.parse(all); dbf.fields.add(field);}
static Field parse(byte[] b) throws IOException {Field field = new Field();BinaryBufferArray t = new BinaryBufferArray(b);field.name = t.ReadAsciiString(11).trim(); //字段名稱field.type = t.ReadAsciiChar(); // 字段類型t.SkipBytes(4);field.length = t.ReadUInt8(); // 字段長度field.precision = t.ReadUInt8(); // 精度t.SkipBytes(2);field.id = t.ReadUInt8();t.SkipBytes(10);field.mdx = t.ReadUInt8();return field;}
解析數(shù)據(jù)代碼:
dbf.resultset = new Vector<Map<String, Object>>(); //結(jié)果集for (int i=0; i<dbf.NumberOfRecords-1; i++) {char delete = '\0'; delete = bis.ReadAsciiChar(); // 讀入刪除標(biāo)記HashMap<String,Object> map = new HashMap<>();for (int j=0; j<dbf.fields.size(); j++) {Field field = dbf.fields.get(j);char type = field.getType();int len = field.getLength();Object val = null;byte[] b = bis.ReadBytes(len); //讀取字段值if (field.getType() == 'N')val = new String(b);else if (field.getType() =='C')val = new String(b, "UTF-8");map.put(field.getName(), val);}map.put("delete", delete);dbf.resultset.add(map);}
讀入dbf文件,解析顯示如下: