将 db 从资产复制到设备数据文件夹时出现 FileNotFoundException
Posted
技术标签:
【中文标题】将 db 从资产复制到设备数据文件夹时出现 FileNotFoundException【英文标题】:FileNotFoundException while copying db from assets to device data folder 【发布时间】:2015-04-08 16:35:15 【问题描述】:我尝试了多种方法将我的 sqlite db 文件复制到我的 /data/data/packagename/databases 文件夹,但我仍然卡在 FileNotFoundException 中,由 FileOutputStream 对象触发... 代码如下:
public static boolean checkCopyDb(Context c, DbHandler _db)
try
String destPath = "/data/data/" + c.getPackageName() + "/databases/db_sociallibraries.db";
File dbFile = new File(destPath);
if(!dbFile.exists())
_db.copyDb(c.getAssets().open(DB_NAME), new FileOutputStream(destPath)); // Line 44 - Throws the exception
return true;
catch (IOException e)
e.printStackTrace();
return false;
private void copyDb(InputStream inputStream, OutputStream outputStream) throws IOException
byte[] buffer = new byte[1024];
int length;
while((length = inputStream.read(buffer)) > 0)
outputStream.write(buffer,0,length);
inputStream.close();
outputStream.close();
这是错误:
02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err: java.io.FileNotFoundException: /data/data/com.test.michelemadeddu.sociallibraries/databases/db_sociallibraries .db:打开失败:ENOENT(没有这样的文件或目录) 02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:在 libcore.io.IoBridge.open(IoBridge.java:409) 02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:在 java.io.FileOutputStream.(FileOutputStream.java:88) 02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:在 java.io.FileOutputStream.(FileOutputStream.java:128) 02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:在 java.io.FileOutputStream.(FileOutputStream.java:117) 02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:在 com.test.michelemadeddu.sociallibraries.DbHandler.checkCopyDb(DbHandler.java:44)
我做错了吗? 谢谢
【问题讨论】:
'c.getPackageName()' 是否返回您所期望的结果? 是的@prudhvi,我也尝试过明确写包名,但结果是一样的。实际上,如果您查看控制台消息,它会说错误在 FileOutPutStream 中,而不是 InputStream 我的假设是,您的文件不存在,因此您的“如果”条件评估为真。检查您是否在该路径中有文件。 我不能@prudhvi,设备本身无法访问该文件夹 【参考方案1】:为了兼容性,也许您可以将内部数据库路径更改为以下
if(android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
【讨论】:
【参考方案2】:请尝试此代码... 这就是我使用的并且工作正常。
只需替换 DB_NAME、DATABASE_NAME 和 DB_PATH 变量即可。
package your.packagename;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class database extends SQLiteOpenHelper
//The Android's default system path of your application database.
private static String DB_PATH = "/data`/data/com.example.applicationame/databases/";`
// Database Name
private static String DB_NAME = "DB.sqlite";
// Logcat tag
private static final String LOG = "database";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "DB.sqlite";
// Table Names
private static final String TABLE_COUNTIES = "Counties";
private static final String TABLE_DESCRIPTIONS = "Descriptions";
private static final String TABLE_NEIGHBORHOODS = "Neighborhoods";
// Common column names
private static final String KEY_ID = "_id";
// TABLE_COUNTIES Table - column names
private static final String COL_COUNTYDETAIL = "countyDetail";
// TABLE_DESCRIPTIONS Table - column names
private static final String COL_DESCRIPTIONDETAIL = "descriptionDetail";
// TABLE_NEIGHBORHOODS Table - column names
private static final String COL_NEIGHBORHOODDETAIL = "neighborhoodDetail";
private SQLiteDatabase myDataBase;
private final Context myContext;
public static long INSERT_ERROR = -1;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public database(Context context)
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException
Log.d(LOG, "Calling checkDataBase() Method");
boolean dbExist = checkDataBase();
if(dbExist)
//do nothing - database already exist
Log.d(LOG, "!!!Database Found!!!");
else
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
Log.d(LOG, "!!!Creating Empy Database!!!");
this.getReadableDatabase();
this.close();
try
Log.d(LOG, "!!!Coping Database!!!");
copyDataBase();
catch (IOException e)
throw new Error(e);
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase()
SQLiteDatabase checkDB = null;
try
String myPath = DB_PATH + DB_NAME;
Log.d(LOG, "looking database at " + myPath);
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
catch(SQLiteException e)
//database does't exist yet.
Log.e(LOG, "Exception: database does't exist yet");
if(checkDB != null)
checkDB.close();
return checkDB != null ? true : false;
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
Log.d(LOG, "Coping database from " + myInput + ", to " + outFileName);
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
myOutput.write(buffer, 0, length);
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
public void openDataBase() throws SQLException
openDataBase(true);
public void openDataBase(boolean readonly) throws SQLException
//Open the database
String myPath = DB_PATH + DB_NAME;
if (readonly)
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
else
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
@Override
public synchronized void close()
if(myDataBase != null)
myDataBase.close();
super.close();
@Override
public void onCreate(SQLiteDatabase db)
// TODO Auto-generated method stub
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
// TODO Auto-generated method stub
我希望它有所帮助。 祝你好运
【讨论】:
以上是关于将 db 从资产复制到设备数据文件夹时出现 FileNotFoundException的主要内容,如果未能解决你的问题,请参考以下文章
将图像从项目资源复制到Objective-C中的文档文件夹时出现问题
将数据从本地复制到 S3 到 Redshift 表时出现问题
运行 rake db:schema:load 时出现“致命:角色“root”不存在”
使用 Hibernate 将 Java 应用程序从 DB2 迁移到 BigQuery 时出现错误“找到:int64,预期:整数”