gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:49:53 25 4
gpt4 key购买 nike

出于某种原因,我无法将软件的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com