import java.io.File; |
02 | import java.io.FileOutputStream; |
03 | import java.io.IOException; |
04 | import java.io.InputStream; |
05 | import android.content.Context; |
06 | /*将assets文件夹下的数据库写入SD卡中 |
07 | * @author Dave */ |
08 | public class WriteToSD { |
09 | private Context context; |
10 | String filePath = android.os.Environment.getExternalStorageDirectory()+ "/mytest" ; |
11 | public WriteToSD(Context context){ |
12 | this .context = context; |
13 | if (!isExist()){ |
14 | write(); |
15 | } |
16 | } |
17 | private void write(){ |
18 | InputStream inputStream; |
19 | try { |
20 | inputStream = context.getResources().getAssets().open( "city.db" ); |
21 | File file = new File(filePath); |
22 | if (!file.exists()){ |
23 | file.mkdirs(); |
24 | } |
25 | FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/database.db" ); |
26 | byte [] buffer = new byte [ 512 ]; |
27 | int count = 0 ; |
28 | while ((count = inputStream.read(buffer)) > 0 ){ |
29 | fileOutputStream.write(buffer, 0 ,count); |
30 | } |
31 | fileOutputStream.flush(); |
32 | fileOutputStream.close(); |
33 | inputStream.close(); |
34 | System.out.println( "success" ); |
35 | } catch (IOException e) { |
36 | e.printStackTrace(); |
37 | } |
38 | } |
39 | private boolean isExist(){ |
40 | File file = new File(filePath + "/database.db" ); |
41 | if (file.exists()){ |
42 | return true ; |
43 | } else { |
44 | return false ; |
45 | } |
46 | } |
47 | } |