0

Androidアプリでリモートsqlite .dbファイルを保存するこのコードがあります:

public String getRemoteCollection(String url, String dbName){
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    dbName="myFile";
    try
    {
        in = new BufferedInputStream(new URL(url).openStream());
        fout = SectionManager.instance.activity.openFileOutput(dbName, Context.MODE_PRIVATE);

        byte data[] = new byte[1024];
        int count;
        while ((count = in.read(data, 0, 1024)) != -1)
            fout.write(data, 0, count);
        if (in != null)
            in.close();
        if (fout != null)
            fout.close();                   
    }
    catch(Exception e){e.printStackTrace();}
    return dbName;
}

私は sqlitemanager でそのファイルを開く必要があり、アセットから .db ファイルを開くこの関数がありますが、このメソッドを適応させて、アセットに保存されていない前述の方法で保存したファイルをロードする必要がありますフォルダ。したがって、この方法を変更する必要がありますが、正しく行う方法がわかりません。

private void generateSQLiteDB(String databaseName) {     // 
        SQLiteDatabase db =  dbHelper.getReadableDatabase(); // by calling this line an empty database will be created into the default system path of this app - we will then overwrite this with the database from the server
        db.close();
        OutputStream os = null;
        InputStream is = null;
        try{
            is =  ctx.getAssets().open(databaseName+".db");
            String packageName=SectionManager.instance.activity.getApplicationContext().getPackageName();
            //os = new FileOutputStream("/data/data/com.android.launcher/databases/"+databaseName+".db");   
            os = new FileOutputStream("/data/data/"+packageName+"/databases/"+databaseName+".db");  
            copyFile(os, is);
        }catch (Exception e) {
            Log.e("DB", "Database not found", e);                          
        }finally{
            try{
                //Close the streams
                if(os != null)
                    os.close();
                if(is != null)
                    is.close();
            } catch (IOException e) {Log.e("DB", "Can't close adapters");}
        }
    }
4

1 に答える 1

1

ドキュメントに記載されているように、openFileOutput() はパスを取りません。ファイルはアプリの「プライベート データ ストレージ」の一部として保存され、デバイス上の他のアプリからはアクセスできません。したがって、上記の 2 つのコード スニペットが同じ Android アプリにあると仮定すると、パスについて心配する必要はありません。同じファイル名を openFileInput() に渡すだけで、保存したものと同じデータが取得されます。

あなたの場合、ファイル名は dbName なので、2 番目のスニペットでは:

is =  ctx.getAssets().open(databaseName+".db");

になる

is = ctx.openFileInput(databaseName);

最初のスニペットで「myFile」にハードコードされているようです。ここでは、ctx が Context 型または Activity などの派生クラスであると想定しています。

更新: アプリのプライベート ファイルの保存に使用されているファイル システム ディレクトリを本当に確認する必要がある場合は、次のように呼び出すことができます。

ctx.getFilesDir();

また

ctx.getFileStreamPath(databaseName);
于 2012-09-11T11:21:05.407 に答える