March 28, 2011

GeoTools DbaseFileReader Sample Code

           
           

I observed that, the code given in geotools documentation  is wrong. The statement missing semi colon and major mistake is DbaseFileReader constructor is passing single argument. Actually there is no such constructor.
This sample code read the DBF file and display the row on console.

I am using NetBeans 6.9.1 , JDK 6 and GeoTools 7.2.1

I used following classes

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel.*;
import org.geotools.data.shapefile.dbf.DbaseFileReader;        


Following code read the DBF file from c: drive with the name jal.dbf. You can change the file name with your file location. You can paste this code to your command button event listener method.

Code:-
File selectedFile = jFileChooser1.getSelectedFile();
FileChannel in = null;
        try {
           in = new FileInputStream(selectedFile).getChannel();        //read the DBF file //Dynamic path
           //in = new FileInputStream("c://jal.dbf").getChannel();       //Static path   
        } catch (FileNotFoundException ex) {
            Logger.getLogger(SearchengineView.class.getName()).log(Level.SEVERE, null, ex);
        }
    DbaseFileReader r = null;
    try {
    r = new DbaseFileReader (in, false,Charset.forName("ISO-8859-1"));  //line was wrong in original code
    } catch (IOException ex1) { }

    Object[] fields = new Object[r.getHeader().getNumFields()];
    while(r.hasNext())
    {
            try {
                r.readEntry(fields);
                System.out.println(r.readRow());   //display the row on console
              } catch (IOException ex) {
                Logger.getLogger(SearchengineView.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
        try {
            r.close();
        } catch (IOException ex) {
            Logger.getLogger(SearchengineView.class.getName()).log(Level.SEVERE, null, ex);
        }

           
           
         

No comments:

Popular Posts