从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();
	}

猜你喜欢

转载自blog.csdn.net/u013183139/article/details/39028267
今日推荐