How to write a database to a text file in android

2019-03-20 16:28发布

问题:

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...

回答1:

You can encode the database file from binary stream to character stream by Base64, then decode the text when nessesary.

First find a Base64 library. You can use http://sourceforge.net/projects/iharder/files/base64/. There's only one file, "Base64.java".

Code example:

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

To revert it, code like following:

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


回答2:

ok guys after a lot of hit and trial i finally found the solution, here is the code, i saved the functionality in a button.

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


            }


        });

the database will be saved in /storage/emulated/0/



回答3:

I would recommend to export into a structered file format such as JSON or CSV. Here is my JSON exporter method. Maybe it helps

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

If you're interested I can also add my CSV exporter.



回答4:

Your question is not that clear (Are you trying to copy the file to an alternative location or export the actual data from it?)

If you only wish to copy the file, you can copy the db file using the following method:

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

Simply call that method with your database file path (/data/data/package_name/databases/database_name) as sourceFileFullPath and your target file path as destFileFullPath. You can than use tools such as SQLite Expert to view the content of the database on your PC/Laptop.

If your intention is to export the data from the database and store it in a text file (a CSV file or anything similar), then you should not read the database file content, and instead use the SQLiteDatabase class to query each table contents into a Cursor and iterate it to write each cursor row into a text file.



回答5:

You could export the entire db into your sdcard folder and then use SQLite manager to open and see it's content.

A Example is available here: http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/



回答6:

Here is the complete method for writing the Database in the SD Card:

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

Hope it will help you.



回答7:

One way to do this (I assume its a long procedure, easy one though), if you know the database and get all the tables and retrieve info from those tables. Since, we are talking about sqlite DBs, I assume it will be small.

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