我在 res/raw/
文件夹中有一个数据库文件。我正在调用 Resources.openRawResource()
,文件名为 R.raw.FileName
,我得到一个输入流,但我在设备中有另一个数据库文件,所以将该数据库的内容复制到我使用的设备数据库:
BufferedInputStream bi = new BufferedInputStream(is);
和 FileOutputStream,但我得到一个数据库文件已损坏的异常。我该如何进行?
我尝试使用 File
和 FileInputStream
读取文件,路径为 /res/raw/fileName
,但这也不起作用。
最佳答案
是的,您应该能够使用 openRawResource
将二进制文件从原始资源文件夹复制到设备。
根据 API 演示 (content/ReadAsset) 中的示例代码,您应该能够使用以下代码 fragment 的变体来读取数据库文件数据。
InputStream ins = getResources().openRawResource(R.raw.my_db_file);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
int size = 0;
// Read the entire resource into a local byte buffer.
byte[] buffer = new byte[1024];
while((size=ins.read(buffer,0,1024))>=0){
outputStream.write(buffer,0,size);
}
ins.close();
buffer=outputStream.toByteArray();
您的文件的副本现在应该存在于 buffer
中,因此您可以使用 FileOutputStream
将缓冲区保存到新文件中。
FileOutputStream fos = new FileOutputStream("mycopy.db");
fos.write(buffer);
fos.close();
关于java - Resources.openRawResource() 问题 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/939170/