Android gets the data in the assets folder and writes it to the SD card example

This example mainly realizes that Android obtains the data in the assets folder and writes it to the SD card. The main steps of the program are: first read the database in the assets folder, and then write it to the SD memory card.

The complete example code is as follows:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
/*将assets文件夹下的数据库写入SD卡中
 * @author Dave */
public class WriteToSD {
 private Context context;
 String filePath = android.os.Environment.getExternalStorageDirectory()+"/weather";
 public WriteToSD(Context context){
 this.context = context;
 if(!isExist()){
  write();
 }
 }
 private void write(){
 InputStream inputStream;
 try {
  inputStream = context.getResources().getAssets().open("addressId.db");
  File file = new File(filePath);
  if(!file.exists()){
  file.mkdirs();
  }
  FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/database.db");
  byte[] buffer = new byte[512];
  int count = 0;
  while((count = inputStream.read(buffer)) > 0){
  fileOutputStream.write(buffer,count);
  }
  fileOutputStream.flush();
  fileOutputStream.close();
  inputStream.close();
  System.out.println("success");
 } catch (IOException e) {
  e.printStackTrace();
 }
 }
 private boolean isExist(){
 File file = new File(filePath + "/database.db");
 if(file.exists()){
  return true;
 }else{
  return false;
 }
 }
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>