Write / Read String Array for android internal storage

I am new to Android development. I am currently developing a simple application for writing and reading String Array to internal memory.

First we have an array, and then save them for storage, then the next activity will load them and assign them to array B. Thanks

+5
source share
3 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 a 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 return the contents of your file in the "Content" line

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

+10
source

If you want to save yourObject to the cache directory, so 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 -

 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(); 
+4
source

On Android, you have several storage options .

If you want to keep an array of strings, use SharedPreferences:

This post may be a solution.

+2
source

Source: https://habr.com/ru/post/1208209/


All Articles