Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap_dataFile / src / org / gvsig / data / datastores / vectorial / file / dbf / utils / DbaseFile.java @ 20626

History | View | Annotate | Download (12.7 KB)

1
/*
2
 * Created on 16-feb-2004
3
 *
4
 * To change the template for this generated file go to
5
 * Window>Preferences>Java>Code Generation>Code and Comments
6
 */
7
package org.gvsig.data.datastores.vectorial.file.dbf.utils;
8

    
9
/**
10
 */
11
import java.io.File;
12
import java.io.IOException;
13
import java.io.RandomAccessFile;
14
import java.nio.ByteBuffer;
15
import java.nio.channels.FileChannel;
16
import java.nio.charset.Charset;
17
import java.text.FieldPosition;
18
import java.text.NumberFormat;
19
import java.util.Calendar;
20
import java.util.Date;
21
import java.util.Locale;
22

    
23
import org.gvsig.data.datastores.vectorial.file.exception.FileNotFoundException;
24
import org.gvsig.data.exception.CloseException;
25
import org.gvsig.data.exception.UnsupportedEncodingException;
26
import org.gvsig.data.exception.UnsupportedVersionException;
27
import org.gvsig.data.exception.WriteException;
28

    
29
import com.iver.utiles.bigfile.BigByteBuffer2;
30

    
31
/**
32
 * Class to read and write data to a dbase III format file. Creation date:
33
 * (5/15/2001 5:15:13 PM)
34
 */
35
public class DbaseFile {
36
        // Header information for the DBase File
37
        private DbaseFileHeader myHeader;
38

    
39
        private File file;
40

    
41
        private RandomAccessFile raf;
42

    
43
        private FileChannel channel;
44

    
45
        private BigByteBuffer2 buffer;
46

    
47
        private FileChannel.MapMode mode;
48

    
49
        private FieldFormatter formatter = new FieldFormatter();
50

    
51
        private int posActual = -1;
52

    
53
        private int recordOffset;
54

    
55
        private ByteBuffer cachedRecord = null;
56

    
57
        private byte[] bytesCachedRecord = null;
58

    
59
        private final Number NULL_NUMBER = new Integer(0);
60

    
61
        private final String NULL_STRING = "";
62

    
63
        private final String NULL_DATE = "        ";
64

    
65
        private Charset chars;
66

    
67

    
68
        /** Utility for formatting Dbase fields. */
69
        public static class FieldFormatter {
70
                private StringBuffer buffer = new StringBuffer(255);
71

    
72
                private NumberFormat numFormat = NumberFormat
73
                                .getNumberInstance(Locale.US);
74

    
75
                private Calendar calendar = Calendar.getInstance(Locale.US);
76

    
77
                private String emtpyString;
78

    
79
                private static final int MAXCHARS = 255;
80

    
81
                public FieldFormatter() {
82
                        // Avoid grouping on number format
83
                        numFormat.setGroupingUsed(false);
84

    
85
                        // build a 255 white spaces string
86
                        StringBuffer sb = new StringBuffer(MAXCHARS);
87
                        sb.setLength(MAXCHARS);
88
                        for (int i = 0; i < MAXCHARS; i++) {
89
                                sb.setCharAt(i, ' ');
90
                        }
91

    
92
                        emtpyString = sb.toString();
93
                }
94

    
95
                public String getFieldString(int size, String s) {
96
                        buffer.replace(0, size, emtpyString);
97
                        buffer.setLength(size);
98

    
99
                        if (s != null) {
100
                                buffer.replace(0, size, s);
101
                                if (s.length() <= size) {
102
                                        for (int i = s.length(); i < size; i++) {
103
                                                buffer.append(' ');
104
                                        }
105
                                }
106
                        }
107

    
108
                        buffer.setLength(size);
109
                        return buffer.toString();
110
                }
111

    
112
                public String getFieldString(Date d) {
113

    
114
                        if (d != null) {
115
                                buffer.delete(0, buffer.length());
116

    
117
                                calendar.setTime(d);
118
                                int year = calendar.get(Calendar.YEAR);
119
                                int month = calendar.get(Calendar.MONTH) + 1; // returns 0
120
                                                                                                                                // based month?
121
                                int day = calendar.get(Calendar.DAY_OF_MONTH);
122

    
123
                                if (year < 1000) {
124
                                        if (year >= 100) {
125
                                                buffer.append("0");
126
                                        } else if (year >= 10) {
127
                                                buffer.append("00");
128
                                        } else {
129
                                                buffer.append("000");
130
                                        }
131
                                }
132
                                buffer.append(year);
133

    
134
                                if (month < 10) {
135
                                        buffer.append("0");
136
                                }
137
                                buffer.append(month);
138

    
139
                                if (day < 10) {
140
                                        buffer.append("0");
141
                                }
142
                                buffer.append(day);
143
                        } else {
144
                                buffer.setLength(8);
145
                                buffer.replace(0, 8, emtpyString);
146
                        }
147

    
148
                        buffer.setLength(8);
149
                        return buffer.toString();
150
                }
151

    
152
                public String getFieldString(int size, int decimalPlaces, Number n) {
153
                        buffer.delete(0, buffer.length());
154

    
155
                        if (n != null) {
156
                                numFormat.setMaximumFractionDigits(decimalPlaces);
157
                                numFormat.setMinimumFractionDigits(decimalPlaces);
158
                                numFormat.format(n, buffer, new FieldPosition(
159
                                                NumberFormat.INTEGER_FIELD));
160
                        }
161

    
162
                        int diff = size - buffer.length();
163
                        if (diff >= 0) {
164
                                while (diff-- > 0) {
165
                                        buffer.insert(0, ' ');
166
                                }
167
                        } else {
168
                                buffer.setLength(size);
169
                        }
170
                        return buffer.toString();
171
                }
172
        }
173

    
174
        public DbaseFile(File afile){
175
                this.file= afile;
176
        }
177

    
178
        // Retrieve number of records in the DbaseFile
179
        public int getRecordCount() {
180
                return myHeader.getNumRecords();
181
        }
182

    
183
        /**
184
         * DOCUMENT ME!
185
         *
186
         * @return DOCUMENT ME!
187
         */
188
        public int getFieldCount() {
189
                return myHeader.getNumFields();
190
        }
191

    
192
        /**
193
         * DOCUMENT ME!
194
         *
195
         * @param rowIndex
196
         *            DOCUMENT ME!
197
         * @param fieldId
198
         *            DOCUMENT ME!
199
         *
200
         * @return DOCUMENT ME!
201
         */
202
        public boolean getBooleanFieldValue(int rowIndex, int fieldId) {
203
                int recordOffset = (myHeader.getRecordLength() * rowIndex)
204
                                + myHeader.getHeaderLength() + 1;
205

    
206
                // Se calcula el offset del campo
207
                int fieldOffset = 0;
208

    
209
                for (int i = 0; i < (fieldId - 1); i++) {
210
                        fieldOffset += myHeader.getFieldLength(i);
211
                }
212

    
213
                buffer.position(recordOffset + fieldOffset);
214

    
215
                char bool = (char) buffer.get();
216

    
217
                return ((bool == 't') || (bool == 'T') || (bool == 'Y') || (bool == 'y'));
218
        }
219

    
220
        /**
221
         * DOCUMENT ME!
222
         *
223
         * @param rowIndex
224
         *            DOCUMENT ME!
225
         * @param fieldId
226
         *            DOCUMENT ME!
227
         *
228
         * @return DOCUMENT ME!
229
         * @throws UnsupportedEncodingException
230
         */
231
        public String getStringFieldValue(int rowIndex, int fieldId) {
232
                int fieldOffset = myHeader.getFieldDescription(fieldId).myFieldDataAddress;
233
                byte[] data = new byte[myHeader.getFieldLength(fieldId)];
234
                if (rowIndex != posActual) {
235
                        recordOffset = (myHeader.getRecordLength() * rowIndex)
236
                                        + myHeader.getHeaderLength() + 1;
237

    
238
                        /*
239
                         * System.err.println("getStringFieldValue: rowIndex = " +
240
                         * rowIndex); System.err.println("recordOffset = " + recordOffset + "
241
                         * fieldOffset=" + fieldOffset);
242
                         */
243
                        buffer.position(recordOffset);
244
                        buffer.get(bytesCachedRecord);
245
                        cachedRecord = ByteBuffer.wrap(bytesCachedRecord);
246
                        posActual = rowIndex;
247

    
248
                }
249
                cachedRecord.position(fieldOffset);
250
                cachedRecord.get(data);
251

    
252
                try {
253
                        return new String(data, chars.name());
254
                } catch (java.io.UnsupportedEncodingException e) {
255
                        new UnsupportedEncodingException("DBF",e);
256
                }
257
                return null;
258

    
259
        }
260

    
261
        public void setFieldValue(int rowIndex, int fieldId, Object obj) throws UnsupportedEncodingException, WriteException {
262
                try{
263
                int fieldOffset = myHeader.getFieldDescription(fieldId).myFieldDataAddress;
264
                String str = fieldString(obj, fieldId);
265
                byte[] data = new byte[myHeader.getFieldLength(fieldId)];
266
                recordOffset = (myHeader.getRecordLength() * rowIndex)
267
                                + myHeader.getHeaderLength() + 1;
268

    
269
                ByteBuffer aux = ByteBuffer.wrap(data);
270
                aux.put(str.getBytes(chars.name()));
271
//                raf.seek(recordOffset + fieldOffset);
272
//                raf.writeBytes(str);
273
                aux.flip();
274
                int numBytesWritten = channel.write(aux, recordOffset + fieldOffset);
275
                //channel.force(true);
276
                }catch (java.io.UnsupportedEncodingException e) {
277
                        throw new UnsupportedEncodingException("DBF",e);
278
                }catch (IOException e) {
279
                        throw new WriteException("DBF",e);
280
                }
281

    
282
        }
283

    
284

    
285
        /**
286
         * Retrieve the name of the given column.
287
         *
288
         * @param inIndex
289
         *            DOCUMENT ME!
290
         *
291
         * @return DOCUMENT ME!
292
         */
293
        public String getFieldName(int inIndex) {
294
                return myHeader.getFieldName(inIndex).trim();
295
        }
296

    
297
        /**
298
         * Retrieve the type of the given column.
299
         *
300
         * @param inIndex
301
         *            DOCUMENT ME!
302
         *
303
         * @return DOCUMENT ME!
304
         */
305
        public char getFieldType(int inIndex) {
306
                return myHeader.getFieldType(inIndex);
307
        }
308

    
309
        /**
310
         * Retrieve the length of the given column.
311
         *
312
         * @param inIndex
313
         *            DOCUMENT ME!
314
         *
315
         * @return DOCUMENT ME!
316
         */
317
        public int getFieldLength(int inIndex) {
318
                return myHeader.getFieldLength(inIndex);
319
        }
320

    
321
        /*
322
         * Retrieve the value of the given column as string.
323
         *
324
         * @param idField DOCUMENT ME! @param idRecord DOCUMENT ME!
325
         *
326
         * @return DOCUMENT ME!
327
         *
328
         * public Object getFieldValue(int idField, long idRecord) throws
329
         * IOException { Object[] tmpReg = getRecord(idRecord); return
330
         * tmpReg[idField]; }
331
         */
332
        /*
333
         * DOCUMENT ME!
334
         *
335
         * @param idField DOCUMENT ME! @param idRecord DOCUMENT ME!
336
         *
337
         * @return DOCUMENT ME!
338
         *
339
         * public double getFieldValueAsDouble(int idField, int idRecord) throws
340
         * IOException { Object[] tmpReg = getRecord(idRecord); return (double)
341
         * Double.parseDouble(tmpReg[idField].toString()); }
342
         */
343

    
344
        /**
345
         * Retrieve the location of the decimal point.
346
         *
347
         * @param inIndex
348
         *            DOCUMENT ME!
349
         *
350
         * @return DOCUMENT ME!
351
         */
352
        public int getFieldDecimalLength(int inIndex) {
353
                return myHeader.getFieldDecimalCount(inIndex);
354
        }
355

    
356
        /**
357
         * read the DBF file into memory.
358
         *
359
         * @param file
360
         *            DOCUMENT ME!
361
         * @throws FileNotFoundException
362
         * @throws UnsupportedVersionException
363
         *
364
         * @throws IOException
365
         *             DOCUMENT ME!
366
         */
367
        public void open() throws FileNotFoundException, UnsupportedVersionException {
368
                /*
369
                 * 01h DOS USA code page 437 02h DOS Multilingual code page 850 03h
370
                 * Windows ANSI code page 1252 04h Standard Macintosh 64h EE MS-DOS code
371
                 * page 852 65h Nordic MS-DOS code page 865 66h Russian MS-DOS code page
372
                 * 866 67h Icelandic MS-DOS 68h Kamenicky (Czech) MS-DOS 69h Mazovia
373
                 * (Polish) MS-DOS 6Ah Greek MS-DOS (437G) 6Bh Turkish MS-DOS 96h
374
                 * Russian Macintosh 97h Eastern European Macintosh 98h Greek Macintosh
375
                 * C8h Windows EE code page 1250 C9h Russian Windows CAh Turkish Windows
376
                 * CBh Greek Windows
377
                 */
378
                try {
379
                if (file.canWrite()) {
380
                        try {
381
                                raf = new RandomAccessFile(file, "rw");
382
                                mode = FileChannel.MapMode.READ_WRITE;
383
                        } catch (java.io.FileNotFoundException e) {
384
                                raf = new RandomAccessFile(file, "r");
385
                                mode = FileChannel.MapMode.READ_ONLY;
386
                        }
387
                } else {
388
                        raf = new RandomAccessFile(file, "r");
389
                        mode = FileChannel.MapMode.READ_ONLY;
390
                }
391
                channel = raf.getChannel();
392

    
393
                // buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0,
394
                // channel.size());
395
                buffer = new BigByteBuffer2(channel, mode);
396

    
397
                // create the header to contain the header information.
398
                myHeader = new DbaseFileHeader();
399
                myHeader.readHeader(buffer);
400
                switch (myHeader.getLanguageID()) {
401
                case 0x01:
402
                        chars = Charset.forName("US-ASCII");
403
                        break;
404
                case 0x02:
405
                        chars = Charset.forName("ISO-8859-1");
406
                        break;
407
                case 0x03:
408
                        chars = Charset.forName("windows-1252");
409
                        break;
410
                case 0x04:
411
                        chars = Charset.forName("mac");
412
                        break;
413
                case 0x64:
414
                        chars = Charset.forName("ISO-8859-1");
415
                        break;
416
                case 0x65:
417
                        chars = Charset.forName("ISO-8859-1");
418
                        break;
419
                case 0x66:
420
                        chars = Charset.forName("ISO-8859-1");
421
                        break;
422
                case 0x67:
423
                        chars = Charset.forName("ISO-8859-1");
424
                        break;
425
                case 0x68:
426
                        chars = Charset.forName("greek");
427
                        break;
428
                case 0x69:
429
                        chars = Charset.forName("ISO-8859-1");
430
                        break;
431
                case 0x6A:
432
                        chars = Charset.forName("greek");
433
                        break;
434
                case 0x6B:
435
                        chars = Charset.forName("ISO-8859-1");
436
                        break;
437

    
438
                default:
439
                        chars = Charset.forName("ISO-8859-1");
440
                }
441
                bytesCachedRecord = new byte[myHeader.getRecordLength()];
442
                }catch (IOException e) {
443
                        throw new FileNotFoundException("DBF",file.getAbsolutePath(),e);
444
                }
445
        }
446

    
447
        /**
448
         * Removes all data from the dataset
449
         * @throws CloseException
450
         *
451
         * @throws IOException
452
         *             DOCUMENT ME!
453
         */
454
        public void close() throws CloseException {
455
                try{
456
                raf.close();
457
                channel.close();
458
                buffer = null;
459
                posActual=-1;
460
                }catch (Exception e) {
461
                        throw new CloseException("DBF",e);
462
                }
463
        }
464

    
465
        public FileChannel getWriteChannel() {
466
                return channel;
467
        }
468

    
469
        private String fieldString(Object obj, final int col) {
470
                String o;
471
                final int fieldLen = myHeader.getFieldLength(col);
472
                switch (myHeader.getFieldType(col)) {
473
                case 'C':
474
                case 'c':
475
                        o = formatter.getFieldString(fieldLen, (obj == null) ? NULL_STRING
476
                                        : ((String) obj));
477
                        break;
478
                case 'L':
479
                case 'l':
480
                        o = (obj == null) ? "F"
481
                                        : ((Boolean) obj).booleanValue() == true ? "T" : "F";
482
                        break;
483
                case 'M':
484
                case 'G':
485
                        o = formatter.getFieldString(fieldLen, (obj == null) ? NULL_STRING
486
                                        : ((String) obj));
487
                        break;
488
                case 'N':
489
                case 'n':
490
                case 'F':
491
                case 'f':
492
                        Number number = null;
493
                        if (obj == null) {
494
                                number = NULL_NUMBER;
495
                        } else {
496
                                Number gVal = (Number) obj;
497
                                number = new Double(gVal.doubleValue());
498
                        }
499
                        o = formatter.getFieldString(fieldLen, myHeader
500
                                        .getFieldDecimalCount(col), number);
501
                        break;
502
                case 'D':
503
                case 'd':
504
                        if (obj == null)
505
                                o = NULL_DATE;
506
                        else
507
                                o = formatter.getFieldString(((Date) obj));
508
                        break;
509
                default:
510
                        throw new RuntimeException("Unknown type "
511
                                        + myHeader.getFieldType(col));
512
                }
513

    
514
                return o;
515
        }
516

    
517
}