java - Save/Read File in android -
i want save file in android , of arraylist deleted after that.i have 2 methods write/read android file here problem want 2 methods that:
the first method must save element of arraylist if call again not write new element in same line write in line
- the second must read line (for example give method line , returns lines contains)
the file looks :
firstelem secondelem thridelem anotherelem ..
is possible in android java? ps: don't need database.
update methods :
private void writetofile(string data) { try { outputstreamwriter outputstreamwriter = new outputstreamwriter(openfileoutput("config.txt", context.mode_private)); outputstreamwriter.write(data); outputstreamwriter.close(); } catch (ioexception e) { log.e("exception", "file write failed: " + e.tostring()); } } private string readfromfile() { string ret = ""; try { inputstream inputstream = openfileinput("config.txt"); if ( inputstream != null ) { inputstreamreader inputstreamreader = new inputstreamreader(inputstream); bufferedreader bufferedreader = new bufferedreader(inputstreamreader); string receivestring = ""; stringbuilder stringbuilder = new stringbuilder(); while ( (receivestring = bufferedreader.readline()) != null ) { stringbuilder.append(receivestring); // stringbuilder.append("\\n"); } inputstream.close(); ret = stringbuilder.tostring(); } } catch (filenotfoundexception e) { log.e("login activity", "file not found: " + e.tostring()); } catch (ioexception e) { log.e("login activity", "can not read file: " + e.tostring()); } return ret; }
using save method linked can create text save stringbuilder
:
public string makearraylistflatfilestring(list<list<string>> listoflists) { stringbuilder sb = new stringbuilder(); if (!listoflists.isempty()) { // assumes lists same length int listlengths = listoflists.get(0).size(); (int i=0; i<listlengths; i++) { (list<string> list : listoflists) { sb.append(list.get(i)).append("\n"); } sb.append("\n"); // blank line after column grouping } } return sb.tostring(); }
to parse contents same file (again assuming equal length lists , string input):
public list<list<string>> getlistoflistsfromflatfile(string data) { // split lines string[] lines = data.split("\\n"); // first find out how many lists we'll need int numberoflists = 0; (string line : lines){ if (line.trim().equals("")) { // blank line means new column grouping stop counting break; } else { numberoflists++; } } // make enough empty lists hold info: list<list<string>> listoflists = new arraylist<list<string>>(); (int i=0; i<numberoflists; i++) { listoflists.add(new arraylist<string>()); } // keep track of list should adding to, , populate lists int listtracker = 0; (string line : lines) { if (line.trim().equals("")) { // new block add next item first list again listtracker = 0; continue; } else { listoflists.get(listtracker).add(line); listtracker++; } } return listoflists; }
Comments
Post a Comment