How can I access an Android resource using RandomAccessFile
in Java?
Here is how I would like this to work (but it doesn't):
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);
}
Log output:
fileIn(6062): ls3d.gold.paper:raw/wwe_obj
The following exception appears in my console:
11-26 15:06:35.027: ERROR/err(6062): java.io.FileNotFoundException: /ls3d.gold.paper:raw/wwe_obj (No such file or directory)
Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works with file as large array of bytes stored in the file system and a cursor using which we can move the file pointer position.
The file will be created if it doesn't exist, but the contents will not be changed if the file does exist because you are opening the file for both reading and writing.
A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read.
RandomAccessFile; public class RandomIO { public static void main(String[] args) throws IOException { // Create a random access file object. RandomAccessFile file = new RandomAccessFile("myfile. dat", "rw"); // Writing to the file. file.
Like you, my situation is much easier if I can use an instance of RandomAccessFile
. The solution I finally arrived at is to simply copy the resource into a file in cache, then open that file with 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;
}
You would use this method thusly:
File cacheFile = createCacheFile(context, resourceId, "delete-me-please");
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile, "r");
// Insert useful things that people want.
randomAccessFile.close();
cacheFile.delete();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With