我正在创建一个需要从文件读取数据的应用程序。我最初是使用 a 来从资产文件夹中读取它的BufferedReader
and an InputStreamReader
但我遇到了内存问题(请参阅Android:文件读取 - 内存不足问题)。一项建议是将数据从资产文件夹复制到内部存储(不是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
我决定使用第二个代码并针对我的文件对其进行修改。所以它看起来像这样:
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
。但是,我从未做过这两项中的任何一项(从资产复制文件并RandomAccessFile
)所以我被困住了。这个应用程序的工作已经陷入停滞,因为这是唯一阻止我完成它的事情。
任何人都可以向我提供如何使用访问数据的更正、建议和正确实现RandomAccessFile
? (数据是每行长度为 4-15 个字符的字符串列表。)
EDIT*
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;
}