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