0

I want to save to a file in android , Some of my arrayList that will be deleted after that.I already have two methods to write/read from android file here but the problem is I want the two methods do that:

  • the first method must save the element of arraylist then if I call it again it will not write the new element in the same line but write it in another line

    • The second must read a line (for example I give to the method which line and it returns what the lines contains)

The file looks like that :

firstelem
secondelem
thridelem

anotherelem
another ..

is this possible to do in android java? PS: I don't need database.

Update This is My 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;
    }
Community
  • 1
  • 1
AndroLife
  • 908
  • 2
  • 11
  • 27

2 Answers2

1

Using the save method you linked to you can create the text to save with a StringBuilder:

public String makeArrayListFlatfileString(List<List<String>> listOfLists)
{
    StringBuilder sb = new StringBuilder();
    if (!listOfLists.isEmpty()) {
        // this assumes all lists are the same length
        int listLengths = listOfLists.get(0).size();
        for (int i=0; i<listLengths; i++)
        {
            for (List<String> list : listOfLists)
            {
                sb.append(list.get(i)).append("\n");
            }
            sb.append("\n");  // blank line after column grouping
        }
    }
    return sb.toString();
}

To parse the contents from that same file (again assuming equal length lists and a String input):

public List<List<String>> getListOfListsFromFlatfile(String data)
{
    // split into lines
    String[] lines = data.split("\\n");
    // first find out how many Lists we'll need
    int numberOfLists = 0;
    for (String line : lines){
        if (line.trim().equals(""))
        {
            // blank line means new column grouping so stop counting
            break;
        }
        else
        {
            numberOfLists++;
        }
    }
    // make enough empty lists to hold the info:
    List<List<String>> listOfLists = new ArrayList<List<String>>();
    for (int i=0; i<numberOfLists; i++)
    {
        listOfLists.add(new ArrayList<String>());
    }
    // keep track of which list we should be adding to, and populate the lists
    int listTracker = 0;
    for (String line : lines)
    {
        if (line.trim().equals(""))
        {
            // new block so add next item to the first list again
            listTracker = 0;
            continue;
        }
        else
        {
            listOfLists.get(listTracker).add(line);
            listTracker++;
        }
    }
    return listOfLists;
}
indivisible
  • 4,892
  • 4
  • 31
  • 50
  • it's not a homework , but a small project to do this is just a part of my project (and I don't have enough time because of that I asked for help). Thank you for the answer ! – AndroLife May 29 '14 at 17:34
  • Ok, in that case, I'll throw in a quick solution for reading too. – indivisible May 29 '14 at 17:42
  • Keep in mind that this will not work if the lists are of differing lengths and is not a great solution for large data sets. – indivisible May 29 '14 at 17:49
0

For writing, just as Illegal Argument states - append '\n':

void writeToFileWithNewLine(String data) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data + "\n");
        outputStreamWriter.close();
    }
    catch (IOException e) { /* handle exception */ } 
}

For reading (just the idea, in practice you should read the file only once):

String readLine(final int lineNo) {
  InputStream in = new FileInputStream("file.txt");
  ArrayList<String> lines = new ArrayList<String>();
  try {
    InputStreamReader inReader = new InputStreamReader(in);
    BufferedReader reader = new BufferedReader(inReader);

    String line;
    do {
      line = reader.readLine();
      lines.add(line);
    } while(line != null);
  } catch (Exception e) { /* handle exceptions */ }
  finally {
    in.close();
  }

  if(lineNo < lines.size() && lineNo >= 0) {
    return lines.get(lineNo);
  } else {
    throw new IndexOutOfBoundsException();
  }
}
Albert Sadowski
  • 642
  • 5
  • 8