如何将数据库的所有值发送到outputstream

时间:2014-10-26 15:17:03

标签: java sqlite

我有一个名为MyDb的SQLite数据库对象。可以通过调用insert Location方法填充此对象。

public boolean insertLocation(String time, double latitude, double longitude) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cV = new ContentValues();
        cV.put("time", time);
        cV.put("latitude", latitude);
        cV.put("longitude", longitude);
        db.insert("location", null, cV);
        return true;
    }

现在我想把所有这些数据都放到输出流中,我该怎么做?

2 个答案:

答案 0 :(得分:0)

返回前

PrintWriter printWriter = new PrintWriter(file); 
printWriter.println("time=" + time);
printWriter.println("latitude=" +latitude);
printWriter.println("longitude=" + longitude);

我希望这可以提供帮助!

答案 1 :(得分:0)

是否要在outputStream中发送数据库中的所有条目?

我试图找到更好的方法,但这是我能想到的:

public void saveDatabaseAsTextFile() {

    // Get a cursor of the data
    Cursor c = doYourQuery();
    if (c.moveToFirst()) {
        try {
            OutputStreamWriter writer = new OutputStreamWriter(
                openFileOutput("locations.txt", Context.MODE_PRIVATE));
            // For each position of the cursor, create a comma
            // delimited string (with a new line char at the end).
            String line;
            do {
                line = "";
                line = line.concat(c.getString(c
                        .getColumnIndex("time")) + ",");
                line = line.concat(c.getDouble(c
                        .getColumnIndex("latitude")) + ",");
                line = line.concat(c.getDouble(c
                        .getColumnIndex("longitude")) + "\n");
                // send the string to the OutputStreamWriter
                writer.write(line);
            } while (c.moveToNext());
            // close the OutputStreamWriter
            writer.close();
        } catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }
}

如果您不想写入文件,请将该字符串抛出到其他OutputStream。