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
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With