如何将数据库写入a​​ndroid中的文本文件

我正在为我的大学项目目的开发间谍应用程序。 为此,我记录了设备的呼叫,位置和SMS,并将它们存储在数据库中。 现在我想将数据库的内容导出到文本文件..我尝试了下面的代码。

private void readAndWriteCallsData() { File dataBaseFile = getDatabasePath("DATABASE"); File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE"); try { BufferedReader dbFileReader = new BufferedReader(new FileReader(callDataFile)); String eachLine; while((eachLine = dbFileReader.readLine()) != null) { Callslog.append(eachLine); Callslog.append("\n"); } } catch (IOException e) { e.printStackTrace(); } } 

但那不行……请帮帮我……

您可以通过Base64将数据库文件从二进制流编码为字符流,然后在必要时解码文本。

首先找到一个Base64库。 您可以使用http://sourceforge.net/projects/iharder/files/base64/ 。 只有一个文件“Base64.java”。

代码示例:

 private void readAndWriteCallsData() { File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE"); try { FileInputStream fis = new FileInputStream(callDataFile); try{ byte[] buf = new byte[512]; int len; while((len = fis.read(buf)) > 0){ String text = Base64.encodeBytes(buf, 0, len); // encode binary to text Callslog.append(text); Callslog.append("\n"); } }finally{ fis.close(); } } catch (IOException e) { e.printStackTrace(); } } 

要还原它,代码如下:

 private void revertCallsData() { File encodedCallDataFile; // get reference to the encoded text file try { BufferedReader br = new BufferedReader(new FileReader(encodedCallDataFile)); try{ String line; while((line = br.readLine()) != null){ byte[] bin = Base64.decode(line); // decode each line to binary, you can get the original database file } }finally{ br.close(); } } catch (IOException e) { e.printStackTrace(); } } 

好的家伙经过大量的点击和试用我终于找到了解决方案,这里是代码,我在一个按钮中保存了function。

 final String SAMPLE_DB_NAME = "MyDBName.db";//database name save.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); FileChannel source=null; FileChannel destination=null; String currentDBPath = "/data/"+ "your package name" +"/databases/"+SAMPLE_DB_NAME; String backupDBPath = SAMPLE_DB_NAME; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); try { source = new FileInputStream(currentDB).getChannel(); destination = new FileOutputStream(backupDB).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); Toast.makeText(getApplicationContext(),"Your database has been exported", Toast.LENGTH_LONG).show(); } catch(IOException e) { e.printStackTrace(); } } }); 

数据库将保存在/ storage / emulated / 0 /

我建议导出为结构化的文件格式,如JSON或CSV。 这是我的JSON导出器方法。 也许有帮助

 private static final String LOG_FOLDER = "/ExportFolder"; private static final String FILE_NAME = "export_file.json"; public static void exportMeasurementsJSON(Handler mHandler) { sendToastMessage("Export to JSON started", mHandler); File folder = new File(Environment.getExternalStorageDirectory() + LOG_FOLDER); if (!folder.exists()) folder.mkdir(); final String filename = folder.toString() + "/" + getLogFileName(".json"); try { FileWriter fw = new FileWriter(filename, false /* append */); // get the db SomeDateSource db = PIApplication.getDB(); // Google Gson for serializing Java Objects into JSON Gson mGson = new GsonBuilder().create(); Cursor c = db.getAllRows(); if (c != null) { while (c.moveToNext()) { fw.append(mGson.toJson(new DBEntry(c .getString(1), c.getString(2), c .getDouble(3), c.getLong(4)))); fw.append('\n'); } c.close(); } fw.close(); sendToastMessage("Export finished", mHandler); } catch (Exception e) { sendToastMessage("Something went wrong", mHandler); e.printStackTrace(); } } 

如果您有兴趣,我也可以添加我的CSV导出器。

您的问题不是那么清楚(您是否尝试将文件复制到其他位置或从中导出实际数据 ?)

如果您只想复制文件,可以使用以下方法复制db文件:

 public static void copyFile(String sourceFileFullPath, String destFileFullPath) throws IOException { String copyFileCommand = "dd if=" + sourceFileFullPath + " of=" + destFileFullPath; Runtime.getRuntime().exec(copyFileCommand); } 

只需使用数据库文件路径( /data/data/package_name/databases/database_name )作为sourceFileFullPath调用该方法,将目标文件路径调用为destFileFullPath 。 您可以使用SQLite Expert等工具查看PC /笔记本电脑上的数据库内容。

如果您打算从数据库导出数据并将其存储在文本文件(CSV文件或类似文件)中,则不应读取数据库文件内容,而应使用SQLiteDatabase类将每个表内容queryCursor并迭代它以将每个游标行写入文本文件。

您可以将整个数据库导出到sdcard文件夹中,然后使用SQLite管理器打开并查看其内容。

这里有一个例子: http : //www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/

以下是在SD卡中编写数据库的完整方法:

 /** * Copy the app db file into the sd card */ private void backupDatabase(Context context) throws IOException { //Open your local db as the input stream String inFileName = "/data/data/yourappPackageName/databases/yourDBName.db"; // OR use- context.getFilesDir().getPath()+"/databases/yourDBName.db";// File dbFile = new File(inFileName); FileInputStream fis = new FileInputStream(dbFile); String outFileName = Environment.getExternalStorageDirectory()+"/"+SQLiteDataHelper.DB_NAME; //Open the empty db as the output stream OutputStream output = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer))>0){ output.write(buffer, 0, length); } //Close the streams output.flush(); output.close(); fis.close(); } 

希望它会对你有所帮助。

一种方法(如果您知道数据库并获取所有表并从这些表中检索信息,我假设它是一个很长的过程,很简单)。 既然,我们正在谈论sqlite DBs,我认为它会很小。

 SELECT * FROM dbname.sqlite_master WHERE type='table';