Android gets the data from the assets folder and writes to the SD card example
- 2020-06-03 08:18:56
- OfStack
The example in this paper mainly realizes that Android obtains the data in assets folder and writes it to SD card. The steps of this program are as follows: first read the database in assets folder and then write it to SD memory card.
The complete sample code is as follows:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
/* will assets Database write under folder SD In the card
* @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, 0 ,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;
}
}
}