6

I am working on a Spying application for my college project purpose. For that i have logged the Calls, Location and SMS of the device and stored them in a database. Now i want to export the contents of the database to a text file.. I tried the below code.

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


}

But that is not working... Please help me...

4

7 回答 7

2

您可以通过 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();
    }
}
于 2013-03-17T16:14:54.693 回答
2

好的,经过大量的尝试和尝试,我终于找到了解决方案,这是代码,我将功能保存在一个按钮中。

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/

于 2015-01-26T12:02:04.677 回答
2

我建议导出为结构化文件格式,例如 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 导出器。

于 2015-01-31T23:37:16.367 回答
1

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

如果您只想复制文件,可以使用以下方法复制 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) assourceFileFullPath和目标文件路径 as调用该方法destFileFullPath。然后,您可以使用诸如SQLite Expert查看 PC/笔记本电脑上的数据库内容之类的工具。

如果您的意图是从数据库中导出数据并将其存储在文本文件(CSV 文件或任何类似文件)中,那么您不应该读取数据库文件内容,而是使用SQLiteDatabase该类将query每个表内容放入 aCursor并进行迭代它将每个光标行写入文本文件。

于 2015-01-26T12:37:14.730 回答
1

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

此处提供了一个示例:http ://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/

于 2015-01-30T05:42:23.313 回答
0

以下是在 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();
    }

希望它会帮助你。

于 2015-01-28T10:49:59.260 回答
-1

如果您知道数据库并获取所有表并从这些表中检索信息,那么一种方法可以做到这一点(我假设它的过程很长,但很简单)。因为,我们谈论的是 sqlite DB,所以我认为它会很小。

SELECT * FROM dbname.sqlite_master WHERE type='table';
于 2013-03-17T18:15:17.943 回答