AndroLife
AndroLife

Reputation: 948

Save/Read File in android

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 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;
    }

Upvotes: 0

Views: 554

Answers (2)

indivisible
indivisible

Reputation: 5012

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;
}

Upvotes: 1

Albert Sadowski
Albert Sadowski

Reputation: 642

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

Upvotes: 0

Related Questions