将字符串数组写入/读取到Android内部存储

5

我是Android开发的新手。目前,我正在开发一个简单的应用程序,用于将String数组写入和读取到内部存储器中。

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


你想在活动关闭后仍然保存数组吗? - Darpan
是的。就像你从互联网下载然后保存,下次只需从内部存储加载。 - Cao Linh Truong
3个回答

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”中获取文件内容。

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


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
在Android上,你有几个存储选项
如果你想要存储一个字符串数组,使用SharedPreferences:
这个帖子可能是一个解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接