從SQLite數據庫導出txt文本文檔

        /**
	 * 導出數據庫
	 * 
	 * @param title
	 * @return
	 */
	public void exportDb(String title) {
		String result[][] = null;
		// 導出
		SQLiteDatabase localSQLiteDatabase = this.dbhelper
				.getWritableDatabase();//
		Cursor cursor = localSQLiteDatabase
				.rawQuery(
						"select noveldetails_detailsid,noveldetails_statrt,"
								+ " noveldetails_pagination,front.novelproperty_pagination from seed,front"
								+ " where seed.novelproperty_propertyid=front.novelproperty_propertyid and "
								+ "front.novelproperty_title =?  order by noveldetails_statrt asc",
						new String[] { title });
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判斷sd卡是否存在
		if (sdCardExist) {
			String baseDir = Environment.getExternalStorageDirectory()
					.getAbsolutePath();// 獲取SD卡目錄
			File file = new File(baseDir + "//" + title + ".txt");

			if (!file.getParentFile().exists()) {// 判斷是否存在,沒創建文件夾
				file.getParentFile().mkdirs();
				// 如:在f盤創建/TXT文件夾/testTXT/兩個文件夾。
			}
			if (!file.exists()) {
				try {
					file.createNewFile();// 創建txt文件 如:testData.txt文件
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			FileWriter fileWriter;
			try {
				OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
						new FileOutputStream(file), "UTF-8");
				// fileWriter = new FileWriter(file, true);
				BufferedWriter bf = new BufferedWriter(outputStreamWriter);

				cursor.moveToNext();
				result = new String[cursor.getCount()][];
				for (int r = 0; r < cursor.getCount(); r++) {
					result[r] = new String[cursor.getColumnCount()];
				}
				for (int r = 0; r < cursor.getCount(); r++) {
					for (int c = 0; c < cursor.getColumnCount(); c++) {
						result[r][c] = cursor.getString(c);
					}
					cursor.moveToNext();
				}
				cursor.close();

				for (String[] str : result) {
					for (String strFile : str) {
						bf.write(strFile);
						bf.flush();
					}
					bf.write("\n"); // 寫入換行
				}
				bf.close();

			} catch (IOException e) {
				e.printStackTrace();
			}
			//
		}
		cursor.close();
		localSQLiteDatabase.close();
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章