由于工作关系,需要工作当中,需要读取DBF文件,找了一些DBF读取开源软件,要么是太过庞大,动不动就上万行,要么是功能有问题,编码,长度,总之是没有找到一个非常爽的。在万般无奈之下,我老人家怒从心头起,恶向胆边生,决定自己写一下。结果只用了不到300行代码就搞定了,当然搞定不是唯一目标,还要优雅简洁的搞定,亲们跟随我的脚步一起感受一下简洁的设计与实现吧。
在开始编码之前,先介绍一下DBF,这个DBF可是个老东西,在DOS时代就已经出现,并且风骚了相当一段时间,后来随着大型数据库的应用,它逐步没落,但是由于其简洁易用的特点,还是应用在大量的数据交换当中。但是其发展过程中,也形成了许多种版本,不同版本的结构不一样,也就决定 了其解析程序也是不一样的。
今天我只实现了Foxbase/DBaseIII的解析,但是也为扩展各种其它版本做好了准备。
接口设计 
上面一共就两个类,一个接口,Field和Header就是两个简单的POJO类,分别定义了文件头及字段相关的信息。
Reader接口是DBF文件读取的接口,主要定义了获取文件类型,编码,字段以及记录移动相关的方法。
代码实现 首先实现Reader的抽象类
1
public abstract class DbfReader implements Reader
{
2
protected String encode = "GBK";
3
private FileChannel fileChannel;
4
protected Header header;
5
protected List<Field> fields;
6
private boolean recordRemoved;
7
int position = 0;
8
static Map<Integer, Class> readerMap = new HashMap<Integer, Class>();
9
10
static
{
11
addReader(3, FoxproDBase3Reader.class);
12
}
13
14
public static void addReader(int type, Class clazz)
{
15
readerMap.put(type, clazz);
16
}
17
18
public static void addReader(int type, String className) throws ClassNotFoundException
{
19
readerMap.put(type, Class.forName(className));
20
}
21
22
public byte getType()
{
23
return 3;
24
}
25
26
public String getEncode()
{
27
return encode;
28
}
29
30
public Header getHeader()
{
31
return header;
32
}
33
34
public List<Field> getFields()
{
35
return fields;
36
}
37
38
39
public boolean isRecordRemoved()
{
40
return recordRemoved;
41
}
42
43
public static Reader parse(String dbfFile, String encode) throws IOException, IllegalAccessException, InstantiationException
{
44
return parse(new File(dbfFile), encode);
45
}
46
47
public static Reader parse(String dbfFile) throws IOException, IllegalAccessException, InstantiationException
{
48
return parse(new File(dbfFile), "GBK");
49
}
50
51
public static Reader parse(File dbfFile) throws IOException, IllegalAccessException, InstantiationException
{
52
return parse(dbfFile, "GBK");
53
}
54
55
public static Reader parse(File dbfFile, String encode) throws IOException, IllegalAccessException, InstantiationException
{
56
RandomAccessFile aFile = new RandomAccessFile(dbfFile, "r");
57
FileChannel fileChannel = aFile.getChannel();
58
ByteBuffer byteBuffer = ByteBuffer.allocate(1);
59
fileChannel.read(byteBuffer);
60
byte type = byteBuffer.array()[0];
61
Class<Reader> readerClass = readerMap.get((int) type);
62
if (readerClass == null)
{
63
fileChannel.close();
64
throw new IOException("不支持的文件类型[" + type + "]。");
65
}
66
DbfReader reader = (DbfReader) readerClass.newInstance();
67
reader.setFileChannel(fileChannel);
68
reader.readHeader();
69
reader.readFields();
70
return reader;
71
}
72
73
public void setFileChannel(FileChannel fileChannel)
{
74
this.fileChannel = fileChannel;
75
}
76
77
78
protected abstract void readFields() throws IOException;
79
80
public void moveBeforeFirst() throws IOException
{
81
position = 0;
82
fileChannel.position(header.getHeaderLength());
83
}
84
85
/** *//**
86
* @param position 从1开始
87
* @throws java.io.IOException
88
*/
89
public void absolute(int position) throws IOException
{
90
checkPosition(position);
91
this.position = position;
92
fileChannel.position(header.getHeaderLength() + (position - 1) * header.getRecordLength());
93
}
94
95
private void checkPosition(int position) throws IOException
{
96
if (position >= header.getRecordCount())
{
97
throw new IOException("期望记录行数为" + (this.position + 1) + ",超过实际记录行数:" + header.getRecordCount() + "。");
98
}
99
}
100
101
protected abstract Field readField() throws IOException;
102
103
protected abstract void readHeader() throws IOException;
104
105
106
private void skipHeaderTerminator() throws IOException
{
107
ByteBuffer byteBuffer = ByteBuffer.allocate(1);
108
readByteBuffer(byteBuffer);
109
}
110
111
public void close() throws IOException
{
112
fileChannel.close();
113
}
114
115
public void next() throws IOException
{
116
checkPosition(position);
117
ByteBuffer byteBuffer = ByteBuffer.allocate(1);
118
readByteBuffer(byteBuffer);
119
this.recordRemoved = (byteBuffer.array()[0] == '*');
120
for (Field field : fields)
{
121
read(field);
122
}
123
position++;
124
}
125
126
public boolean hasNext()
{
127
return position < header.getRecordCount();
128
}
129
130
private void read(Field field) throws IOException
{
131
ByteBuffer buffer = ByteBuffer.allocate(field.getLength());
132
readByteBuffer(buffer);
133
field.setStringValue(new String(buffer.array(), encode).trim());
134
field.setBuffer(buffer);
135
}
136
137
protected void readByteBuffer(ByteBuffer byteBuffer) throws IOException
{
138
fileChannel.read(byteBuffer);
139
}
140
}
141
这个类是最大的一个类,值得注意的是几个静态方法: addReader和parse, addReader用于增加新的类型的Reader,parse用于解析文件。
parse的执行过程是首先读取第一个字节,判断是否有对应的解析实现类,如果有,就有对应的解析实现类去解析,如果没有,则抛出错误声明不支持。
下面写实现类就简单了,下面是FoxproDBase3的解析器:
1
public class FoxproDBase3Reader extends DbfReader
{
2
protected void readFields() throws IOException
{
3
fields = new ArrayList<Field>();
4
for (int i = 0; i < (header.getHeaderLength() - 32 - 1) / 32; i++)
{
5
fields.add(readField());
6
}
7
}
8
9
public byte getType()
{
10
return 3;
11
}
12
13
protected Field readField() throws IOException
{
14
Field field = new Field();
15
ByteBuffer byteBuffer = ByteBuffer.allocate(32);
16
readByteBuffer(byteBuffer);
17
byte[] bytes = byteBuffer.array();
18
field.setName(new String(bytes, 0, 11, encode).trim().split("\0")[0]);
19
field.setType((char) bytes[11]);
20
field.setDisplacement(Util.getUnsignedInt(bytes, 12, 4));
21
field.setLength(Util.getUnsignedInt(bytes, 16, 1));
22
field.setDecimal(Util.getUnsignedInt(byt 1
public class DbfReaderTest
{
2
static String[] files =
{"BESTIMATE20140401", "BHDQUOTE20140401"};
3
4
public static void main(String[] args) throws IOException, IllegalAccessException, InstantiationException
{
5
for (String file : files)
{
6
printFile(file);
7
}
8
}
9
10
public static void printFile(String fileName) throws IOException, InstantiationException, IllegalAccessException
{
11
Reader dbfReader = DbfReader.parse("E:\\20140401\\" + fileName + ".DBF");
12
for (Field field : dbfReader.getFields())
{
13
System.out.printf("name:%s %s(%d,%d)\n", field.getName(), field.getType(), field.getLength(), field.getDecimal());
14
}
15
System.out.println();
16
for (int i = 0; i < dbfReader.getHeader().getRecordCount(); i++)
{
17
dbfReader.next();
18
for (Field field : dbfReader.getFields())
{
19
System.out.printf("%" + field.getLength() + "s", field.getStringValue());
20
}
21
System.out.println();
22
}
23
dbfReader.close();
24
25
}
26
} es, 17, 1));
23
field.setFlag(bytes[18]);
24
return field;
25
}
26
27
protected void readHeader() throws IOException
{
28
header = new Header();
29
ByteBuffer byteBuffer = ByteBuffer.allocate(31);
30
readByteBuffer(byteBuffer);
31
byte[] bytes = byteBuffer.array();
32
header.setLastUpdate((Util.getUnsignedInt(bytes, 0, 1) + 1900) * 10000 + Util.getUnsignedInt(bytes, 1, 1) * 100 + Util.getUnsignedInt(bytes, 2, 1));
33
header.setRecordCount(Util.getUnsignedInt(bytes, 3, 4));
34
header.setHeaderLength(Util.getUnsignedInt(bytes, 7, 2));
35
header.setRecordLength(Util.getUnsignedInt(bytes, 9, 2));
36
}
37
}
测试用例 可以看到最后的使用也是非常简洁的。 代码统计 
总共的代码行数是282行,去掉import和接口声明之类的,真正干活的代码大概就200行了:
总结 上面不仅展示了如何实现DBF文件的解析,同时还展示了如何在现在面临的需求与未来的扩展进行合理均衡的设计方式。
比如:要实现另外一个标准的DBF文件支持,只要类似上面FoxproDBase3Reader类一样,简单实现之后,再调用DbfParser.addReader(xxxReader);
好的设计需要即避免过度设计,搞得太复杂,同时也要对未来的变化与扩展做适当考虑,避免新的需求来的时候需要这里动动,那里改改导致结构上的调整与变化,同时要注意遵守DRY原则,可以这样说如果程序中有必要的大量的重复,就说明一定存在结构设计上的问题。
欢迎关注:http://web.j2ee.top。本例涉及的代码和框架资料,将会在这里分享。也欢迎进加入QQ群:228977971,让我们一起成长!
posted on 2015-06-08 23:26
柏然 阅读(75)
评论(0) 编辑 收藏