【问题标题】:How to write a database to a text file in android如何在android中将数据库写入文本文件
【发布时间】:2013-03-17 14:38:19
【问题描述】:

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

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


}

但这不起作用...请帮助我...

【问题讨论】:

  • 您的代码没有作家(所有读者)!请解释什么不起作用?
  • 其实你可以这样做......但你只是在文本文件中获取二进制数据。也许你可以把你的 db 文件,重命名为正确的文本格式,你会得到你需要的。
  • @AlekseyMaximus 请输入密码
  • 您的意思是将数据库文件保存到简单的文本文件中吗?
  • @hasan 你在找什么样的文本格式?

标签: java android sqlite


【解决方案1】:

您可以通过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();
    }
}

【讨论】:

  • 我是 Android 新手。你能用代码解释一下吗?数据库文件名为“DATABASE”。现在如何将该数据写入文本文件。 请编码 谢谢:)
  • 我尝试了编码部分,但仍然出现错误...E/AndroidRuntime(16078): java.lang.RuntimeException: Unable to start service com.innolabs.spydroid.WriteFromDataBase@405464a0 with Intent { flg=0x4 cmp=com.innolabs.spydroid/.WriteFromDataBase (has extras) }: java.lang.NullPointerException com.innolabs.spydroid.WriteFromDataBase.readAndWriteDataseFiles(WriteFromDataBase.java:81) E/AndroidRuntime(16078): at com.innolabs.spydroid.WriteFromDataBase.onStartCommand(WriteFromDataBase.java:29)我在 CallsLog.append(text); 处遇到错误
  • 把readAndWriteDataseFiles方法贴一下,肯定有问题。
  • private void readAndWriteDataseFiles() throws IOException { InputStream myinput = getAssets().open("DATABASE"); String outfilename = Environment.getDataDirectory()+"/data/com.example.app/databases/"+ "DATABASE"; System.out.println("outfilename"+outfilename); OutputStream output = new FileOutputStream(outfilename); byte[] buffer = new byte[1024]; int length; while ((length = myinput.read(buffer)) > 0) { myoutput.write(buffer,0,length); } output.flush(); output.close(); myinput.close(); }
  • 检查上面的代码。我发现了另一种方式......这个链接就像魅力一样 - stackoverflow.com/questions/9138601/…..
【解决方案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/

【讨论】:

  • 这不是db-dump,更像是复制db文件,还是需要sqlite应用才能打开那个文件吧?
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

    如果你只想复制文件,可以使用以下方法复制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 类到 query 每个表内容到 Cursor 并迭代它以将每个光标行写入文本文件。

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        【解决方案6】:

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

        希望对你有所帮助。

        【讨论】:

          【解决方案7】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-05-15
            • 1970-01-01
            • 1970-01-01
            • 2017-03-21
            • 2014-06-02
            • 2017-03-23
            • 1970-01-01
            相关资源
            最近更新 更多