我有这个代码用我的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文件,但我需要调整这个方法来加载我在前面提到的方法中存储的文件,这不是存储在assets文件夹中。所以我必须改变这种方法,但我不知道如何正确地做到这一点。
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");}
}
}
答案 0 :(得分:1)
openFileOutput(),正如文档所述,不采用路径,文件存储为应用程序的“私有数据存储”的一部分,设备上的其他应用程序无法访问该文件。因此,假设您上面的两个代码段位于同一Android应用中,您无需担心路径,只需将相同的文件名传递给openFileInput(),您就会得到与存储的数据相同的数据。
在您的情况下,您的文件名是dbName,因此在您的第二个代码段中:
is = ctx.getAssets().open(databaseName+".db");
变为
is = ctx.openFileInput(databaseName);
似乎在第一个片段中硬编码为“myFile”。我在这里假设ctx是Context类型或派生类,如Activity。
更新:如果您确实需要查找用于存储应用私人文件的文件系统目录,可以致电:
ctx.getFilesDir();
或
ctx.getFileStreamPath(databaseName);