android - 将 Arraylist 保存到文件 android

标签 android arraylist file-handling

我正在这里做我的第一个 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" />

在我的 list 中。

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

最佳答案

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

要将文件写入外部存储,请使用 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");
    }
}

关于android - 将 Arraylist 保存到文件 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28768704/

相关文章:

java - 使用数字和范围对字符串列表进行排序

java - 检查数组列表中的项目是否是在另一个类中创建的对象的实例

java - System.getProperty ("line.separator"之间的区别;和 "\n"?

c++ - 如何将文件的特定部分读入私有(private)数据成员

android - SoundPool 在两种情况下崩溃。第一个场景崩溃的代码

android - 获得 visibility=gone 的 View 的高度

android 挂起而 android 找不到连接

java - 根据某些字段对对象进行分组

python - 我只想从测试文件中删除一个搜索行

android - MediaRecorder 抛出 illegalstateexception