来自资源的Android RandomAccessFile用法

时间:2011-11-26 14:10:13

标签: java android

如何使用Java中的RandomAccessFile访问Android资源?

以下是我希望如何工作(但事实并非如此):

String fileIn = resources.getResourceName(resourceID);
Log.e("fileIn", fileIn);
//BufferedReader buffer = new BufferedReader(new InputStreamReader(fileIn));

RandomAccessFile buffer = null;
try {
  buffer = new RandomAccessFile(fileIn, "r");
} catch (FileNotFoundException e) {
  Log.e("err", ""+e);
}

日志输出:

fileIn(6062): ls3d.gold.paper:raw/wwe_obj

我的控制台中出现以下异常:

11-26 15:06:35.027: ERROR/err(6062): java.io.FileNotFoundException: /ls3d.gold.paper:raw/wwe_obj (No such file or directory)

3 个答案:

答案 0 :(得分:2)

和我一样,如果我可以使用RandomAccessFile的实例,我的情况会更容易 。我最终得到的解决方案是简单地将资源复制到缓存中的文件中,然后使用RandomAccessFile打开该文件:

/**
 * Copies raw resource to a cache file.
 * @return File reference to cache file.
 * @throws IOException
 */
private File createCacheFile(Context context, int resourceId, String filename)
    throws IOException {
  File cacheFile = new File(context.getCacheDir(), filename);

  if (cacheFile.createNewFile() == false) {
    cacheFile.delete();
    cacheFile.createNewFile();
  }

  // from: InputStream to: FileOutputStream.
  InputStream inputStream = context.getResources().openRawResource(resourceId);
  FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
  int count;
  byte[] buffer = new byte[1024 * 512];
  while ((count = inputStream.read(buffer)) != -1) {
    fileOutputStream.write(buffer, 0, count);
  }

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

  return cacheFile;
}

你会这样使用这个方法:

File cacheFile = createCacheFile(context, resourceId, "delete-me-please");
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile, "r");

// Insert useful things that people want.

randomAccessFile.close();
cacheFile.delete();

答案 1 :(得分:0)

它是一个FileNotFound异常。这意味着您没有指定要在String fileIn = resources.getResourceName(resourceID);

打开的文件

问题是,Android只能返回原始文件的InputStreamFileDescriptor,但这两者对于RandomAccessFile构造函数来说都不够。

有一个名为Unified I/O的开源库,您可以使用它来实现您想要的,但我认为它只会使您的项目“更重”。也许你应该想到,如果你能以某种方式避免RandomAccessFile。

答案 2 :(得分:-1)

我正在使用此代码:

public static String readContentFromResourceFile(Context context, int resourceId)
throws IOException {
    StringBuffer sb = new StringBuffer();
    final String NEW_LINE = System.getProperty("line.separator");

    InputStream is = context.getResources().openRawResource(resourceId);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String readLine = null;

    try {
        while ((readLine = br.readLine()) != null) {
            sb.append(readLine);
            sb.append(NEW_LINE);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        br.close();
        is.close();
    }

    return sb.toString();
}