我在我的Android设备有多个.CSV文件的文件夹。
我想所有的人都导入到我的SQLite数据库,但每个文件必须是不同的表。
所有的.csv文件中简单。 他们只有一个列。
例:
FILE.CSV
12345
123
00000000
AnotherFile.CSV
XXXXX
ZZZZZZZZZZ
FFFF
这里是我的方法,它是行不通的。 我不明白为什么:
@TargetApi(Build.VERSION_CODES.M)
public void importaTabelas() {
//Check the read permission
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
//Check if the folder exists
File importDir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ENEL/IMPORTADOS/");
if (!importDir.exists())
{
importDir.mkdirs();
}
//Read all file names
for (File f : importDir.listFiles()) {
if (f.isFile()) {
//Put the files names into variable nomeArq
nomeArq = f.getName();
//Take off the file extension .csv
if (nomeArq.indexOf(".") > 0)
nomeArq = nomeArq.substring(0, nomeArq.lastIndexOf("."));
SQLiteDatabase db = this.banco.getWritableDatabase();
try {
//Create table with the name of the .csv file
String criaTab = "CREATE TABLE IF NOT EXISTS " + nomeArq + " (id integer PRIMARY KEY AUTOINCREMENT, codigo varchar (50))";
db.execSQL(criaTab);
db.close();
} catch (SQLException e) {
e.printStackTrace();
}
//String for the file location
String fn = importDir + "/" + nomeArq + ".csv";
//Reads the file
FileReader fileReader = new FileReader(fn);
BufferedReader buffer = new BufferedReader(fileReader);
//ContentValues contentValues = new ContentValues();
String line = "";
//db.beginTransaction();
while ((line = buffer.readLine()) != null) {
//String[] colums = line.split("\t");
//String[] colums = line.split(";");
Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
//contentValues.put("codigo", line);
//db.insert(nomeArq, null, contentValues);
db.execSQL("INSERT INTO " + nomeArq + " (codigo) VALUES ('" + line + "')");
}
//db.setTransactionSuccessful();
//db.endTransaction();
}
}
} catch (Exception e) {
Toast.makeText(this, "Catch!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
else {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}
你能帮我做它的工作原理? 谢谢!