我有三个单独的文件解析函数,它们将文本文件转换为对象,然后将这些值插入到 sqlite 数据库中。除了对象类之外,它们基本上都是相同的。
过程如下:
- 使用 http 下载文件
- 计算文件中的行数以进行进度计算
- 删除目标表中所有以前的记录
- 使用 BufferedReader 打开文件
- 一次读取 2000 行并将其转换为对象
- 在事务中将 2000 条记录插入到 sqlite
- 循环直到完成
我无法弄清楚如何使这段代码通用以允许任何类用于创建对象,然后决定使用哪个 DAL 函数来持久化数据。Java 不是我的第一语言,所以任何指导都会很棒。
这是我正在使用的代码:
public void downloadPendingPoleInspections() {
int count;
String filePath;
Inspections inspections = Inspections.getInstance();
filePath = Environment.getExternalStorageDirectory() + File.separator + "inspections.txt";
try {
downloadFile("http://localhost/api/inspectionservices.aspx?o=retrieve", "pendinginspections.txt", POST_PENDING_INSPECTIONS_PROGRESS_UPDATE);
int totalInspections = getLineCount(filePath);
inspections.deleteAllPendingInspections();
File file = new File(filePath);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i = 0;
int j = 0;
List<PendingInspection> batch = new ArrayList<PendingInspection>();
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
PendingInspection pending = new PendingInspection(
Integer.parseInt(values[0]), values[1],
Double.parseDouble(values[2]),
Double.parseDouble(values[3]));
batch.add(pending);
i++;
j++;
if (i >= 2000) {
inspections.pendingInspectionsBatchInsert(batch);
batch.clear();
i = 0;
}
}
if (i > 0) {
inspections.pendingInspectionsBatchInsert(batch);
batch.clear();
}
br.close();
file.delete();
} catch (Exception e) {
Log.e("SyncActivity", e.toString());
}
}
编辑:这是接口和类声明
public interface Inspectable {
public int getId();
public void setId(int id);
public String getLabel();
public void setLabel(String label);
public double getX();
public void setX(double x);
public double getY();
public void setY(double y);
}
public class RWInspection {
private String id;
private double x;
private double y;
private String inspector;
private String comments;
private String timestamp;
public RWInspection(String id, double x, double y, String inspector, String comments, String timestamp) {
this.id = id;
this.x = x;
this.y = y;
this.inspector = inspector;
this.comments = comments;
this.timestamp = timestamp;
}
snip.... getter 和 setter 实现
public class PInspection implements Inspectable{
private int id;
private String number;
private double x;
private double y;
public PInspection(int id, String poleNumber, double x, double y) {
this.id = id;
this.number = number ;
this.x = x;
this.y = y;
}