ファイルからデータを読み取る必要があるアプリを作成しています。最初はとを使用してアセットフォルダーから読み取っていましたBufferedReader
が、InputStreamReader
メモリの問題が発生していました(Android:ファイルの読み取り-OutOfMemoryの問題を参照)。1つの提案は、アセットフォルダーから内部ストレージ(SDカードではない)にデータをコピーしてから、を介してアクセスすることRandomAccessFile
でした。そこで、アセットから内部ストレージにファイルをコピーする方法を調べたところ、2つのソースが見つかりました。
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/RpXiMYV48Ww
http://developergoodies.blogspot.com/2012/11/copy-android-asset-to-internal-storage.html
2番目のコードを使用して、ファイル用に変更することにしました。したがって、次のようになります。
public void copyFile() {
//Open your file in assets
Context context = getApplicationContext();
String destinationFile = context.getFilesDir().getPath() + File.separator + "text.txt";
if (!new File(destinationFile).exists()) {
try {
copyFromAssetsToStorage(context, "text.txt", destinationFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int length = Input.read(buffer);
while (length > 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
}
private void copyFromAssetsToStorage(Context context, String sourceFile, String destinationFile) throws IOException {
InputStream inputStream = context.getAssets().open(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile);
copyStream(inputStream , outputStream );
outputStream.flush();
outputStream.close();
inputStream.close();
}
これにより、ファイルがアプリのデータディレクトリにコピーされると想定しています。を使用してファイルにアクセスできるようにしたいため、テストできませんでしたRandomAccessFile
。ただし、これら2つのいずれか(アセットからファイルをコピーするRandomAccessFile
)を実行したことがないため、スタックします。このアプリの作業は、これが私がそれを完了するのを妨げている唯一のことであるため、停止しました。
誰かが私に、を使用してデータにアクセスする方法の修正、提案、および正しい実装を提供できますRandomAccessFile
か?(データは、各行の長さが4〜15文字のストリングのリストです。)
編集*
private File createCacheFile(Context context, String filename){
File cacheFile = new File(context.getCacheDir(), filename);
if (cacheFile.exists()) {
return cacheFile ;
}
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = context.getAssets().open(filename);
fileOutputStream = new FileOutputStream(cacheFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ( (length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer,0,length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return cacheFile;
}