Cao Linh Truong
Cao Linh Truong

Reputation: 253

Write/Read String Array to internal storage 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

Upvotes: 5

Views: 5987

Answers (3)

Darpan
Darpan

Reputation: 5795

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();

Upvotes: 4

Nipper
Nipper

Reputation: 2380

On Android you have several storage options.

If you want to store a string array, use SharedPreferences:

This post might be a solution.

Upvotes: 2

Yoganand.N
Yoganand.N

Reputation: 907

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

Upvotes: 10

Related Questions