Android:使用RandomAccessFile从内部存储访问文件 [英] Android: Accessing File from Internal Storage Using RandomAccessFile

查看:820
本文介绍了Android:使用RandomAccessFile从内部存储访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个需要从文件中读取数据的应用程序。我最初使用 BufferedReader InputStreamReader 从assets文件夹中读取它,但是我遇到了内存问题Android:文件读取 - OutOfMemory问题)。一个建议是将资产文件夹中的数据复制到内部存储器(不是SD卡),然后通过 RandomAccessFile 进行访问。所以我查了一下如何将资源中的文件复制到内部存储中,我发现有两个来源:

https://groups.google.com/forum/?fromgroups=#!topic/android-developers/RpXiMYV48Ww



http://developergoodies.blogspot.com/2012/11/copy-android-asset-to-internal-storage.html



我决定使用第二个代码并将其修改为我的文件。所以它看起来像这样:

$ pre $ public $ copyFile(){
//在资产中打开你的文件
上下文context = getApplicationContext();
String destinationFile = context.getFilesDir()。getPath()+ File.separator +text.txt; (b)(b)(b)(b)(b)(b)(b)
} 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);


$ b 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();



$ b $ p
$ b

我假设这个文件复制到应用程序的数据目录中。我一直无法测试它,因为我希望能够使用 RandomAccessFile 来访问文件。但是,我从来没有做过这两个(从资产复制文件和 RandomAccessFile ),所以我卡住了。这个应用程序的工作已经停滞,因为这是唯一阻止我完成它的东西。

任何人都可以使用 RandomAccessFile 来提供更正,建议和正确的数据访问方式吗? (数据是每行有4-15个字符的字符串列表)。

编辑*

  private文件createCacheFile(Context context,String filename){
File cacheFile = new File(context.getCacheDir(),filename);

if(cacheFile.exists()){
return cacheFile;
}

InputStream inputStream = null;
FileOutputStream fileOutputStream = null;

尝试{

inputStream = context.getAssets()。open(filename);
fileOutputStream = new FileOutputStream(cacheFile);

int bufferSize = 1024;
byte [] buffer = new byte [bufferSize];
int length = -1; ((length = inputStream.read(buffer))> 0){
fileOutputStream.write(buffer,0,length);

$ b $ catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
finally {
try {
fileOutputStream.close();
} catch(IOException e){
e.printStackTrace();
}
尝试{
inputStream.close();
} catch(IOException e){
e.printStackTrace();
}
}

return cacheFile;


解决方案

资产到缓存目录

这段代码只是为了说明,你必须做适当的异常处理和关闭资源

pre $私有文件createCacheFile(上下文上下文,字符串文件名){
文件cacheFile = new File(context.getCacheDir() , 文件名);

if(cacheFile.exists()){
return cacheFile;


$ b InputStream inputStream = context.getAssets()。open(filename);
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);

int bufferSize = 1024;
byte [] buffer = new byte [bufferSize];
int length = -1; ((length = inputStream.read(buffer))> 0){
fileOutputStream.write(buffer,0,length);
}

fileOutputStream.close();
inputStream.close();

return cacheFile;

$ / code>

使用 RandomAccessFile
$ p $ File cacheFile = createCacheFile(context,text.txt);
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile,r);

//处理文件

randomAccessFile.close();

请注意,您应遵循Java的命名约定。你的方法和变量名应该以小写字母开头,例如 copyFromAssetsToStorage destinationFile



编辑:

您应该制作一个单独的 try / catch 对于每个 close()操作,所以如果一个失败,另一个仍然被执行,并检查它们是不是 null

  finally {
如果(fileOutputStream!= null){
fileOutputStream。关();
}
} catch(IOException e){
e.printStackTrace();


try {
if(inputStream!= null){
inputStream.close();
}
} catch(IOException e){
e.printStackTrace();
}
}


I am creating an app that needs to read data from a file. I was initially reading it from the assets folder using a BufferedReader and an InputStreamReader but I was running into memory issues (see Android: File Reading - OutOfMemory Issue). One suggestion was to copy the data from the assets folder to the internal storage (not the SD card) and then access it via RandomAccessFile. So I looked up how to copy files from the assets to internal storage and I found 2 sources:

https://groups.google.com/forum/?fromgroups=#!topic/android-developers/RpXiMYV48Ww

http://developergoodies.blogspot.com/2012/11/copy-android-asset-to-internal-storage.html

I decided to use the code from the second one and modified it for my file. So it looks like this:

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();
}

I am assuming that this copies the file into the app's data directory. I have not been able to test it because I would like to be able to access the file using RandomAccessFile. However, I have never done either one of these two (copying the file from assets and RandomAccessFile) so I am stuck. The work on this app has come to a standstill because this is the only thing that is preventing me from completing it.

Can anyone provide me with corrections, suggestions, and correct implementations of how to access the data using RandomAccessFile? (The data is a list of strings 4-15 characters in length on each line.)

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;
}

解决方案

1- Copy the file from assets to the cache directory

This code just for illustration, you have to do appropriate exception handling and close resources

private File createCacheFile(Context context, String filename){
  File cacheFile = new File(context.getCacheDir(), filename);

  if (cacheFile.exists()) {
      return cacheFile ;
  }


  InputStream inputStream = context.getAssets().open(filename);
  FileOutputStream 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);
  }

  fileOutputStream.close();
  inputStream.close();

  return cacheFile;
}

2- Open the file using RandomAccessFile

File cacheFile = createCacheFile(context, "text.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile, "r");

// Process the file

randomAccessFile.close();    

On a side note, you should follow Java naming conventions, e.g. your method and variable name should start with small letter such as copyFromAssetsToStorage and destinationFile

Edit:

You should make a separate try/catch for each close() operation, so if one fails the other still get executed and check that they are not null

finally {
    try {
       if(fileOutputStream!=null){
          fileOutputStream.close();            
       }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
      if(inputStream!=null){
       inputStream.close();      
      }      
    } catch (IOException e) {
        e.printStackTrace();
    }
}  

这篇关于Android:使用RandomAccessFile从内部存储访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆