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

Cao*_*ong 5 arrays android

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

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

Yog*_*d.N 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();
    }
Run Code Online (Sandbox Code Playgroud)

要从文件中读取:

    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 "";
    }
Run Code Online (Sandbox Code Playgroud)

因此,您将在字符串"contents"中找回您的文件内容

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


Dar*_*pan 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();
Run Code Online (Sandbox Code Playgroud)

读回来 -

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();
Run Code Online (Sandbox Code Playgroud)