JNIを使用してCから.txtファイルなどのAndroidアセットにアクセスするにはどうすればよいですか?
「file:/// android_asset / myFile.txt」を試し、ローカルで「myFile.txt」を使用して、C実装ファイルを含むjniフォルダーにmyFile.txtを複製します。
JNIを使用してCから.txtファイルなどのAndroidアセットにアクセスするにはどうすればよいですか?
「file:/// android_asset / myFile.txt」を試し、ローカルで「myFile.txt」を使用して、C実装ファイルを含むjniフォルダーにmyFile.txtを複製します。
アセットの問題は、ファイルとして直接アクセスできないことです。これは、アセットが APK から直接読み取られるためです。インストール時に特定のフォルダーに解凍されません。
Android 2.3 以降、アセットにアクセスするための C API があります。<android/asset_manager.h>
と のassetManager
フィールドを見てください<android/native_activity.h>
。私はこれを使用したことがありません。また、ネイティブ アクティビティに依存しない場合、このアセット マネージャー API を使用できるかどうかもわかりません。とにかく、これは Android 2.2 以下では動作しません。
したがって、次の 3 つのオプションがあります。
InputStream
ですAssetManager.open()
。少しコードが必要ですが、うまく機能します。ファイル名を必要とするC/C++ライブラリを呼び出す必要があるためにAssetManager C APIを使用できない場合は、代わりに生のリソースを使用できます。
唯一の欠点は、実行時にアプリのデータ (一時) ディレクトリにコピーする必要があることです。
ネイティブ コードから読み取りたいファイルをres/raw
dir に配置します。
res/raw/myfile.xml
実行時に、次のディレクトリにファイルをコピーしますdata
。
File dstDir = getDir("data", Context.MODE_PRIVATE);
File myFile = new File(dstDir, "tmp_myfile.xml");
FileMgr.copyResource(getResources(), R.raw.my_file, myFile);
ネイティブ コードに渡すファイル名は次のとおりです。myFile.getAbsolutePath()
public static File copyResource (Resources r, int rsrcId, File dstFile) throws IOException
{
// load cascade file from application resources
InputStream is = r.openRawResource(rsrcId);
FileOutputStream os = new FileOutputStream(dstFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1)
os.write(buffer, 0, bytesRead);
is.close();
os.close();
return dstFile;
}