Import-Export data file
I'm storing my data to a file in /data/data/.....! And i want to add an import-export feature in my app that backups the file in the SDCARD and import it(and the app automatically read it). How can i doing this ? Thank you. So is that true ?
public class Import {
public static void transfer(){
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/SDCARD/Carburant");
dir.mkdirs();
copyfile("/data/data/carburant.android.com/files/","/SDCARD/Carburant/storeddata");
}
private static void copyfile(String srFile, String dtFile){
try{
File f1 = new File("/data/data/carburant.android.com/files/");
File f2 = new File("/SD开发者_JS百科CARD/Carburant/storeddata");
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
}
first of all you need to assure you have the right permissions to read/write data.
Then, you can get the directory for your application like this:
String myDir = act.getFilesDir();
Regarding Android's security and sandboxing, your application will only be able to read/write to this directory, I think. Although SDCard access is more open:
You can call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream.
A good example is given here in stackoverlow.
精彩评论