Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write/Read String Array to internal storage android

Tags:

arrays

android

I am new to android development. Currently, i am developing a simple app for writing and reading a String Array to an internal storage.

First we have A array then save them to storage, then next activity will load them and assign them to array B. Thank you

like image 353
Cao Linh Truong Avatar asked Dec 03 '14 06:12

Cao Linh Truong


2 Answers

To write to a file:

    try {
        File myFile = new File(Environment.getExternalStorageDirectory().getPath()+"/textfile.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.write("replace this with your string");
        myOutWriter.close(); 
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

To read from the file:

    String pathoffile;
    String contents="";

    File myFile = new File(Environment.getExternalStorageDirectory().getPath()+"/textfile.txt");
    if(!myFile.exists()) 
    return "";
    try {
        BufferedReader br = new BufferedReader(new FileReader(myFile));
        int c;
        while ((c = br.read()) != -1) {
            contents=contents+(char)c;
        }

    }
    catch (IOException e) {
        //You'll need to add proper error handling here
        return "";
    }

Thus you will get back your file contents in the string "contents"

Note: you must provide read and write permissions in your manifest file

like image 125
Yoganand.N Avatar answered Sep 20 '22 05:09

Yoganand.N


If you wish to store yourObject to cache directory, this is how you do it-

String[] yourObject = {"a","b"};
    FileOutputStream stream = null;

    /* you should declare private and final FILENAME_CITY */
    stream = ctx.openFileOutput(YourActivity.this.getCacheDir()+YOUR_CACHE_FILE_NAME, Context.MODE_PRIVATE);
    ObjectOutputStream dout = new ObjectOutputStream(stream);
    dout.writeObject(yourObject);

    dout.flush();
    stream.getFD().sync();
    stream.close();

To read it back -

String[] readBack = null;

FileInputStream stream = null;

    /* you should declare private and final FILENAME_CITY */
    inStream = ctx.openFileInput(YourActivity.this.getCacheDir()+YOUR_CACHE_FILE_NAME);
    ObjectInputStream din = new ObjectInputStream(inStream );
    readBack = (String[]) din.readObject(yourObject);

    din.flush();

    stream.close();
like image 33
Darpan Avatar answered Sep 19 '22 05:09

Darpan