写/读字符串数组到内部存储android

时间:2014-12-03 06:17:20

标签: android arrays

我是Android开发的新手。目前,我正在开发一个简单的应用程序,用于编写和读取字符串数组到内部存储。

首先我们有一个数组然后将它们保存到存储中,然后下一个活动将加载它们并将它们分配给数组B.谢谢

3 个答案:

答案 0 :(得分:10)

要写入文件:

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

从文件中读取:

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

因此,您将在字符串“contents”

中找回文件内容

注意:您必须在清单文件中提供读写权限

答案 1 :(得分:4)

如果您希望将yourObject存储到缓存目录,请执行以下操作 -

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

要读回来 -

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

答案 2 :(得分:2)

在Android上,你有几个storage options

如果要存储字符串数组,请使用SharedPreferences:

post可能是一种解决方案。