[英]Import multiple .csv file into android sqlite database
我现在正在尝试从android设备从sd卡中的某个目录导入csv文件。 最近,我可以成功导入单个csv文件。 但是,我不知道如何获取所有csv文件的列表,然后使用循环逐个导入csv文件的想法。
这是我导入单个csv的代码:
button_import_csv.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
try{
FileReader file = new FileReader("/sdcard/downloadedfolder/A1/adv_sales_order.csv");
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues=new ContentValues();
String line = "";
String tableName ="adv_sales_order";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split("\t");
contentValues.put("order_date", str[0]);
contentValues.put("cust_code", str[1]);
contentValues.put("customer_ref_no", str[2]);
contentValues.put("line_no", str[3]);
contentValues.put("item_code", str[4]);
contentValues.put("tran_code", str[5]);
contentValues.put("order_qty", str[6]);
db.insert(tableName, null, contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
}catch (IOException e){
}
}
});
不同csv文件S的列不相同。(例如,有些可能有4个列,分别命名为A,B,C,D,另一个可能具有名为C,D,E,F的列)除了对所有列进行硬编码之外对于每个csv文件,有没有可能的方法? 谁能告诉我任何解决方案?谢谢。
我可以想到两种可能性...
首先:如果您可以控制文件名,则给它们起一个具有连续数字意义的名称,例如file1.csv,file2.csv等。然后,您可以简单地使用for
循环来构建文件名并进行处理。 例...
// Lets say you have 5 files named file1.csv thru file5.csv
for(int i = 1; i < 6; i++) {
String filename = "file" + i + ".csv";
// Process the file which has the above filename
}
第二:使用listFiles()
方法获取目录中的所有文件。 例...
// This code assumes you have a File object for the directory called dir
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++) {
String filename = files[i].getAbsolutePath();
if (filename.endsWith(".csv")) {
// Process the file which has the above filename
}
}
我不确定上面的代码块是否完美,但是基本上它们都只是使用for
循环。 还有其他方法,但是最直接的方法。
编辑:某些csv文件使用第一行来描述列名称。 在某些方面,这有点像数据集的架构。 示例(使用逗号分隔的值)...
A,B,C,D
valueA,valueB,valueC,valueD
...
使用这种方法意味着您可以通过读取第一行并将其拆分为一个数组来访问列名。 然后,您可以使用for
循环放置ContentValues。 尝试以下...
// Read the first line separately and split to get the column names
line = buffer.readLine();
String[] cols = line.split("\t");
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split("\t");
for (int i = 0; i < cols.length; i++) {
contentValues.put(cols[i], str[i]);
}
db.insert(tableName, null, contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
顺便说一句,我注意到您正在分割"\\t"
因此请确保第一行上的列名以制表符分隔(显然)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.