将Arraylist保存到文件android

凯文·布朗

我正在这里做我的第一个Android应用程序,我正在尝试将写入ArrayList<String>文件,然后将其读回。

这是我编写文件的代码:

(该类称为SaveFiles)

public static void writeList(Context c, ArrayList<String> list){
        try{
            FileOutputStream fos = c.openFileOutput("NAME", Context.MODE_PRIVATE);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(list);
            os.close();
Log.v("MyApp","File has been written");
        }catch(Exception ex){
            ex.printStackTrace();
Log.v("MyApp","File didn't write");
        }
    }

我还没有代码来读取文件。

调用此方法的代码:

//TempArrays.loadCustomTitles() loads a pre-created file that has entities 

    SaveFiles.writeList(getApplicationContext(), TempArrays.loadCustomTitles());

日志显示该文件已创建,但是在手机上找不到该文件,我从字面上看应该在该文件的所有位置,因此它是隐藏的,或者更确切地说,是未创建的。

我宣布

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在我的清单上。

有人知道这是怎么回事吗?

拉维(Ravi K Thapliyal)

您看不到该文件,因为您使用openFileOutput()它在设备的内部存储目录上创建了该文件。此处创建的文件是您的应用程序私有的,用户甚至看不到。如果用户卸载应用程序,这些文件将被自动删除。

要将文件写入外部存储,请使用getExternalStoragePublicDirectory()方法。

// check if sd card is mounted and available for read & write
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    try {
            // create a file in downloads directory
            FileOutputStream fos =
              new FileOutputStream(
                new File(Environment.getExternalStoragePublicDirectory(
                  Environment.DIRECTORY_DOWNLOADS), "name.ser")
            );
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(list);
            os.close();
            Log.v("MyApp","File has been written");
    } catch(Exception ex) {
            ex.printStackTrace();
            Log.v("MyApp","File didn't write");
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章