怎么样把txt文件的数据导入到sqlite里去?
解决方案
20
主要代码如下:
try {
File txt = new File(SDCARD_PATH + “/file//file.txt”); // txt文件
br = new BufferedReader(new FileReader(txt));
db = DatabaseManager.getInstance().openDatabase();
db.execSQL(“create table if not exists file_table(number integer,”
+ “name integer,”
+ “bh char(50),”
+ “nl char(50),”
+ “jl char(50))”);
Cursor cursors = db
.query(“file_table”, null, null, null, null, null, null);
if (cursors.getCount() != 0) {
br.close();
cursors.close();
return;
}
cursors.close();
// 读取直到最后一行
String line = “”;
if ((line = br.readLine()) != null) {
// line = br.readLine();
}
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, “,”);
ContentValues contentValues = new ContentValues();
int i = 0;
while (st.hasMoreTokens()) {
// 每一行的多个字段用TAB隔开表示
String currentString = st.nextToken();
System.out.print(currentString + “\t”);
if (i == 0) {
contentValues.put(“number”, currentString);
}
if (i == 1) {
contentValues.put(“name”, currentString);
}
if (i == 2) {
contentValues.put(“bh”, currentString);
}
if (i == 3) {
contentValues.put(“nl”, currentString);
}
if (i == 4) {
contentValues.put(“jl”, currentString);
}
++i;
Log.v(TAG, currentString);
}
System.out.println();
db.insert(“file_table”, null, contentValues);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
File txt = new File(SDCARD_PATH + “/file//file.txt”); // txt文件
br = new BufferedReader(new FileReader(txt));
db = DatabaseManager.getInstance().openDatabase();
db.execSQL(“create table if not exists file_table(number integer,”
+ “name integer,”
+ “bh char(50),”
+ “nl char(50),”
+ “jl char(50))”);
Cursor cursors = db
.query(“file_table”, null, null, null, null, null, null);
if (cursors.getCount() != 0) {
br.close();
cursors.close();
return;
}
cursors.close();
// 读取直到最后一行
String line = “”;
if ((line = br.readLine()) != null) {
// line = br.readLine();
}
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, “,”);
ContentValues contentValues = new ContentValues();
int i = 0;
while (st.hasMoreTokens()) {
// 每一行的多个字段用TAB隔开表示
String currentString = st.nextToken();
System.out.print(currentString + “\t”);
if (i == 0) {
contentValues.put(“number”, currentString);
}
if (i == 1) {
contentValues.put(“name”, currentString);
}
if (i == 2) {
contentValues.put(“bh”, currentString);
}
if (i == 3) {
contentValues.put(“nl”, currentString);
}
if (i == 4) {
contentValues.put(“jl”, currentString);
}
++i;
Log.v(TAG, currentString);
}
System.out.println();
db.insert(“file_table”, null, contentValues);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}