在android系统中,外部文件有两种存储方式:内置于asset和raw文件夹内。然而系统只提供了InputStream的读接口。java中常用的RandomFileAccess和FileReader等不能不能直接实现InputStream接口。经过查阅网上提供了以下两种折中的方法用来实现以上接口:
方法一:
InputStream转FileReader(http://stackoverflow.com/questions/2860157/load-files-bigger-than-1m-from-assets-folder )
代码如下:
File f = File.createTempFile("mytempfile", "dat");
FileOutputStream fos = new FileOutputStream(f);
InputStream is = mc.getAssets().open(path,3);
ObjectInputStream ois=new ObjectInputStream(is);
byte[] data = (byte[]) ois.readObject();
fos.write(data);
fos.flush();
fos.close();
InputStream转RandomAccessFile(http://www.coderanch.com/t/277378/Streams/java/InputStream-RandomAccessFile-best-way )
代码如下:
RandomAccessFile raf = new RandomAccessFile(File.createTempFile("isc", "tmp"), "rwd");
byte[] buffer = new byte[2048];
int tmp = 0;
while ((tmp = is.read(buffer)) != -1)
{
raf.write(buffer, 0, tmp);
}
raf.seek(0);
以上两种方法通过建立tmpFile从而实现基于File的文件读写类,该方法的缺陷也显而易见占用内存,每个文件都要被读写多次导致程序效率低下。虽然在android下文件不能超过1M,但是针对现有手机的硬件,多次存取会导致不论从耗电量还是程序的速度都会有明显的影响。
This file can not be opened as a file descriptor; it is probably compressed
见引用http://code.google.com/p/android/issues/detail?id=3122