通过文件的方式保存内容

来源:互联网 发布:vue.js怎么用 编辑:程序博客网 时间:2024/05/16 13:54

在android系统中,存储器一般分为外存储器(sdcard)和内存储器,一般内存器是手机自带的,内存储器和外存器的区别如下:

内存储器总是可用的,安装默认也是安装在这里,内容只能被自己的应用读取。

外存储器正好相反。

读写存储器的许可:

<manifest ...>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    ...</manifest>
<manifest ...>    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />    ...</manifest>
保存内容在内存储器中:

getFilesDir():得到文件目录

getCacheDir():得到缓存目录

创建一个新文件:

File file = new File(context.getFilesDir(), filename);或
String filename = "myfile";String string = "Hello world!";FileOutputStream outputStream;try {  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);  outputStream.write(string.getBytes());  outputStream.close();} catch (Exception e) {  e.printStackTrace();}
下一个方法示例是从URL中得到一个文件名,并在缓存中创建它;
public File getTempFile(Context context, String url) {    File file;    try {        String fileName = Uri.parse(url).getLastPathSegment();        file = File.createTempFile(fileName, null, context.getCacheDir());    catch (IOException e) {        // Error while creating file    }    return file;}
在外部的存储器中读写文件
/* 检查在外存器是否是可用的 */public boolean isExternalStorageWritable() {    String state = Environment.getExternalStorageState();    if (Environment.MEDIA_MOUNTED.equals(state)) {        return true;    }    return false;}/* Checks if external storage is available to at least read */public boolean isExternalStorageReadable() {    String state = Environment.getExternalStorageState();    if (Environment.MEDIA_MOUNTED.equals(state) ||        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {        return true;    }    return false;}
在外部存储器中分为两类文件:
私有文件和公共文件,以下的例子是它们的区别
public File getAlbumStorageDir(String albumName) {    // Get the directory for the user's public pictures directory.     File file = new File(Environment.getExternalStoragePublicDirectory(            Environment.DIRECTORY_PICTURES), albumName);    if (!file.mkdirs()) {        Log.e(LOG_TAG, "Directory not created");    }    return file;}
public File getAlbumStorageDir(Context context, String albumName) {    // Get the directory for the app's private pictures directory.     File file = new File(context.getExternalFilesDir(            Environment.DIRECTORY_PICTURES), albumName);    if (!file.mkdirs()) {        Log.e(LOG_TAG, "Directory not created");    }    return file;}
查询文件的空间通过getFreeSpace() or getTotalSpace().
对于扩展卡可以通过:
getExtSDCardPath();方法取得路径。
删除文件通过myFile.delete();
当应用删除时,所有在内存储器上的和在外存储器上的内容都会被删除。



0 0