怎样在程序初次运行时将预制的数据库拷贝到指定位置

Android 码拜 9年前 (2015-05-10) 990次浏览 0个评论
 

新人求教

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;

public class InitActivity extends Activity {

	String Path = "mnt/data/data/com.wrdggess.init/databases";
	String dbName = "gess.db";
	Context context = this.getBaseContext();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_init);
		copyDb(Path);
	}

	public void copyDb(String path) {       
		File file = new File(Path, dbName);   //获取参数
		if (!file.exists()) {     
			file.getParentFile().mkdirs();   //判断文件是否存在
			}     
		InputStream iStream = this.getBaseContext().getResources()     
				.openRawResource(R.raw.gess);   //提取数据库文件
		try {     
			FileOutputStream fos = new FileOutputStream(file);      
			byte[] buffer = new byte[1024];    
			int count = 0;     // 将静态数据库文件拷贝到目的地    
			while ((count = iStream.read(buffer)) > 0) {     
				fos.write(buffer, 0, count);    
				}     
			fos.close();    
			fos.close();     
			Toast.makeText(context, "本地数据库加载成功", Toast.LENGTH_SHORT).show(); 
		} catch (FileNotFoundException e) {    // TODO Auto-generated catch block    
		  e.printStackTrace();   
		  } catch (IOException e) {     // TODO Auto-generated catch block    
			  Toast.makeText(context, "本地数据库加载失败", Toast.LENGTH_SHORT).show();    
			  e.printStackTrace();   
			  }    
		  }

}

上面的代码执行后没有创建databases文件夹,即使我在虚拟机里自建了databases文件夹也不能拷贝

40分
while ((count = iStream.read(buffer)) > 0) {     
                fos.write(buffer, 0, count);    
}   

判断是不是错了?
源码里说了:
Returns the number of bytes actually read or -1 if the end of the stream has been reached.
应该是判断-1吧,不然会无限循环的

引用 1 楼 inquisitive_plus 的回复:
while ((count = iStream.read(buffer)) > 0) {     
                fos.write(buffer, 0, count);    
}   

判断是不是错了?
源码里说了:
Returns the number of bytes actually read or -1 if the end of the stream has been reached.
应该是判断-1吧,不然会无限循环的

已经解决了,事实上只是我路径搞错了,抱歉


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎样在程序初次运行时将预制的数据库拷贝到指定位置
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!