Friday, December 10, 2010

Android file read write simple

public class ReadNWriteFile extends Activity {

 final String TEST_STRING = new String("Hello Android");
 final String FILE_NAME = "SAMPLEFILE.txt";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  TextView tv = new TextView(this);
  fileCreate();
  tv.setText(readFile());
  setContentView(tv);
 }

 private void fileCreate() {
  try {
   OutputStream os = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
   OutputStreamWriter osw = new OutputStreamWriter(os);
   osw.write(TEST_STRING);
   osw.close();
  } catch (Exception e) {
   Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
  }
 }

 private String readFile() {
  try {
   FileInputStream fin = openFileInput(FILE_NAME);
   InputStreamReader isReader = new InputStreamReader(fin);
   char[] buffer = new char[TEST_STRING.length()];
   // Fill the buffer with data from file
   isReader.read(buffer);
   return new String(buffer);
  } catch (Exception e) {
   Log.i("ReadNWrite, readFile()", "Exception e = " + e);
   return null;
  }
 }
}
 
 
 your serializable data save or load on file 
 
/**
     * internal data storage
     */
    public static void saveCache(String filename, Serializable settings, Activity act)
            throws IOException {

        FileOutputStream fos = act.openFileOutput(filename, Context.MODE_PRIVATE);

        OutputStream buffer = new BufferedOutputStream(fos);
        ObjectOutput output = new ObjectOutputStream(buffer);
        try {
            output.writeObject(settings);
        } finally {
            output.close();
        }
    }

    /**
     * internal data storage
     */
    public static Serializable openCache(String filename, Activity act)
            throws IOException {

        FileInputStream fis = act.openFileInput(filename);

        InputStream buffer = new BufferedInputStream(fis);
        ObjectInput input = new ObjectInputStream(buffer);
        try {
            return (Serializable) input.readObject();
        } catch (Exception ex) {
            throw new IOException(ex.getMessage());
        } finally {
            input.close();
        }
    } 

No comments: