Android, ¿cómo verificar si el archivo existe y, de lo contrario, crear uno?
Tengo la siguiente pregunta. Me gustaría colocar un archivo llamado data.xml en la carpeta sdcard / appname y usarlo para leer y escribir datos de la aplicación.
Entonces, cuando se crea mi actividad principal, necesito verificar si este archivo existe:
public class appname extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.no_elements_l);
File file = getBaseContext().getFileStreamPath("/sdcard/appname/data.xml");
if(file.exists()) {
return;
} else {
// create a File object for the parent directory
File MTdirectory = new File("/sdcard/appname/");
// have the object build the directory structure, if needed.
MTdirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(MTdirectory, "data.xml");
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream DataFile = new FileOutputStream(outputFile);
}
Pero tengo el tipo de excepción no controlada FileNotFoundException en la última línea. ¿Cuál es el problema? Utiliza el permiso WRITE_EXTERNAL_STORAGE se agrega al manifiesto.