在android中保存/读取文件

时间:2014-05-29 16:54:09

标签: java android arraylist android-file

我想保存到android中的一个文件,我的一些arrayList将在那之后被删除。我已经有两种方法可以从android文件here写入/读取但问题是我想要两种方法那样做:

  • 第一种方法必须保存arraylist的元素然后如果我再次调用它,它将不会在同一行中写入新元素,而是将其写入另一行

    • 第二个必须读一行(例如我给方法哪一行,它返回行包含的内容)

该文件如下:

firstelem
secondelem
thridelem

anotherelem
another ..

这可以在android java中做到吗? PS:我不需要数据库。

更新的 这是我的方法:

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

2 个答案:

答案 0 :(得分:1)

使用您链接到的保存方法可以创建要使用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();
}

解析同一文件中的内容(再次假设长度列表和字符串输入相等):

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

答案 1 :(得分:0)

对于写作,正如非法论证所述 - 追加'\ 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 */ } 
}

为了阅读(只是想法,在实践中你应该只阅读一次文件):

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