In Java, you can use the Apache Commons IO and Apache Commons DbUtils libraries to process files in the DBF (dBase file) format. Use the FileUtils class to read the DBF file, and then use the DbfReader class to parse the file contents. To write to a DBF file, use the DbfWriter class to create and write the file, specifying field names and data.
In Java, you can use third-party libraries to read and write files in DBF (dBase file) format. The following is a basic example of using Apache Commons IO and Apache Commons DbUtils libraries to read and write DBF files:
1. Reading DBF files
Use the FileUtils class in the Apache Commons IO library to read a DBF file and then use the DbfReader class from the Apache Commons DbUtils library to parse the file contents.
import org.apache.commons.io.FileUtils;import org.apache.commons.dbutils.DbfReader;import java.io.File;import java.io.FileInputStream;public class DbfFileReader { public static void main(String[] args) { try { File dbfFile = new File("path/to/your/dbf/file.dbf"); FileInputStream inputStream = new FileInputStream(dbfFile); DbfReader reader = new DbfReader(inputStream); Object[] row; while ((row = reader.nextRecord()) != null) { // 处理每一行数据 for (Object value : row) { System.out.print(value + " "); } System.out.println(); } reader.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
2. Write DBF files
Use the DbfWriter class in the Apache Commons DbUtils library to create and write DBF files.
import org.apache.commons.dbutils.DbfWriter;import org.apache.commons.dbutils.io.DbfFileWriter;import java.io.File;import java.io.FileOutputStream;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;public class DbfFileWriter { public static void main(String[] args) { try { File dbfFile = new File("path/to/new/dbf/file.dbf"); FileOutputStream outputStream = new FileOutputStream(dbfFile); Charset charset = Charset.forName("GBK"); // 使用指定字符集 List<String> fieldNames = new ArrayList<>(); fieldNames.add("Field1"); fieldNames.add("Field2"); // 添加更多字段名 List<Object[]> data = new ArrayList<>(); data.add(new Object[]{"value1", 123}); data.add(new Object[]{"value2", 456}); // 添加更多数据 DbfWriter writer = new DbfWriter(outputStream, charset); writer.setFields(fieldNames); for (Object[] row : data) { writer.write(row); } writer.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
In these examples, we used the FileUtils class from the Apache Commons IO library to read the file, and then used the DbfReader and DbfWriter classes from the Apache Commons DbUtils library to read and write the contents of the DBF file . Please make sure you have included the dependencies for these libraries and filled in the path and filename with the correct values.
The above is the detailed content of How to read and write java dbf files. For more information, please follow other related articles on the PHP Chinese website!