Android --- APK をパッケージ化するときに、data/data/パッケージ名/databases/ にあるデータベース ファイルを一緒にパッケージ化できない問題を解決するにはどうすればよいですか?

実はとてもシンプルです

準備したデータベース ファイルを、一緒にパッケージ化できるパスであるプロジェクト ディレクトリ Assets の下に配置し、assets の下のデータベース ファイルを data/data/パッケージ名/databases/ にコピーします。コア コードは次のとおりです。

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();
				}
			}
		}
	}
}

おすすめ

転載: blog.csdn.net/qq_43290288/article/details/130283302