java - 无法将 SQLite 数据库从 Assets 复制到另一个区域

标签 java android libgdx

出于某种原因,我无法将软件的 SQLite 数据库从“assets”文件夹复制到其他目的地。使用我正在使用的“copyDatabaseFromAssets() ”方法,它只会生成一个空文件。我确实修剪了以下代码,以便更容易找到错误消息。

由于我的想法不足,I used an old article from ReignDesign.com稍微调整数据库文件。我也碰巧使用了 2016 版的 SQLDroid,它似乎工作正常。

文件位于“~/assets/database/test.db”。

这是我使用的基本代码:

public class AndroidLauncher extends AndroidApplication {

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );

        copyDatabaseFromAssets( this, "test.db", true );

    }


    /**
     * Copy database file from assets folder inside the apk to the system database path.
     * @param context Context
     * @param databaseName Database file name inside assets folder
     * @param overwrite True to rewrite on the database if exists
     * @return True if the database have copied successfully or if the database already exists without overwrite, false otherwise.
     */
    private boolean copyDatabaseFromAssets( Context context, String databaseName, boolean overwrite )  {

        File outputFile = context.getDatabasePath( databaseName );


        if ( outputFile.exists() && !overwrite ) {

            return true;

        }

        outputFile = context.getDatabasePath( databaseName + ".temp" );
        outputFile.getParentFile().mkdirs();


        try {

            InputStream inputStream = context.getAssets().open( databaseName );
            OutputStream outputStream = new FileOutputStream( outputFile );


            // transfer bytes from the input stream into the output stream
            byte[] buffer = new byte[ 1024 ];
            int length;

            while ( ( length = inputStream.read( buffer ) ) > 0 ) {

                outputStream.write( buffer, 0, length );

            }

            // Close the streams
            outputStream.flush();
            outputStream.close();
            inputStream.close();

            outputFile.renameTo( context.getDatabasePath( databaseName ) );

        } catch ( IOException e ) {

            if ( outputFile.exists() ) {

                outputFile.delete();

            }

            return false;

        }

        return true;

    }


}

谢谢。

最佳答案

您的数据库文件位于子文件夹内,从子文件夹获取文件的更好方法只需更改此行

InputStream inputStream = context.getAssets().open( databaseName );

收件人:

InputStream inputStream = context.getAssets().open("database/" + databaseName);

希望对您有所帮助!

关于java - 无法将 SQLite 数据库从 Assets 复制到另一个区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50984267/

相关文章:

java - 将 JFileChooser 置于所有窗口之上

android - Opengl - 将纹理转换为数组

java - 约束连接/绳索/线以避免拉伸(stretch)

Java libgdx - 设置每个屏幕的方向

java - 当我尝试在 java 中实现 appium-flutter-driver 时,appium-flutter-finder 依赖项不起作用有人知道如何修复它吗?

java - 使用位操作将 Byte[] 转换为 Long

android - 无法在模拟器中启动 AVD。 sh : grep: command not found

java - Android 位图缩小

java - 高分未保存在 Libgdx 中

java - firestore -- 在 hashmap 的字段中添加元素