Android --- How to solve the problem that the database files under data/data/package name/databases/ cannot be packaged together when packaging APK?

It's actually very simple

We put the prepared database file under the project directory assets, which is the path that can be packaged together, and then copy the database file under assets to data/data/package name/databases/. The following is the core code :

private static final String DB_NAME = "abc.db"; // 数据库名
private static final String DATA_BASE_PATH = "/data/data/com.abc/databases/";
private static final int BUFFER_SIZE = 9000; // 根据数据库文件大小扩大

private void copyfile() {
    
    
	File dir = new File(DATA_BASE_PATH);
	if (!dir.exists()) {
    
    
		dir.mkdirs();
	}
	File file = new File(DATA_BASE_PATH + DB_NAME);
	if (!file.exists()) {
    
    
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
    
    
			inputStream = mContext.getAssets().open(DB_NAME);
			outputStream = new FileOutputStream(file);
			byte[] buffer = new byte[BUFFER_SIZE];
			int length;
			while ((length = inputStream.read(buffer, 0, buffer.length)) > 0) {
    
    
				outputStream.write(buffer, 0, length);
			}
			outputStream.flush();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			if (inputStream != null) {
    
    
				try {
    
    
					inputStream.close();
				} catch (IOException e) {
    
    
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
    
    
				try {
    
    
					outputStream.close();
				} catch (IOException e) {
    
    
					e.printStackTrace();
				}
			}
		}
	}
}

Guess you like

Origin blog.csdn.net/qq_43290288/article/details/130283302