jueves, junio 09, 2011

Write a text file in Android using the emulator in Eclipse

///
/// check read/write permissions

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
Log.i(TAG,"read + write");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
Log.i(TAG,"read");
} else {
// Something else is wrong. It may be one of many other states, but all we need
//  to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
Log.i(TAG,"nothing");
}

///
/// write text file

File testFile = new File(Environment.getExternalStorageDirectory()+"/test.txt");
try{
testFile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
//we have to bind the new file with a FileOutputStream
FileOutputStream os = null;        
try{
os = new FileOutputStream(testFile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}

PrintWriter pw = new PrintWriter(os);

pw.println("test");
pw.close();

Log.i(TAG,"wrote in: " + Environment.getExternalStorageDirectory()+ "/test.txt");

No hay comentarios: