在android程序下,如果我们应用在当前包下创建了一个文件,并且我们希望别的应用程序 可以访问我们的文件 ,这时候我们需要给这个文件设置一个mode参数,如下:
/**
* File creation mode: the default mode, where the created file can only
* be accessed by the calling application (or all applications sharing the
* same user ID).
* @see #MODE_WORLD_READABLE
* @see #MODE_WORLD_WRITEABLE
*/
public static final int MODE_PRIVATE = 0x0000;
/**
* File creation mode: allow all other applications to have read access
* to the created file.
* @see #MODE_PRIVATE
* @see #MODE_WORLD_WRITEABLE
*/
public static final int MODE_WORLD_READABLE = 0x0001;
/**
* File creation mode: allow all other applications to have write access
* to the created file.
* @see #MODE_PRIVATE
* @see #MODE_WORLD_READABLE
*/
public static final int MODE_WORLD_WRITEABLE = 0x0002;
/**
* File creation mode: for use with {@link #openFileOutput}, if the file
* already exists then write data to the end of the existing file
* instead of erasing it.
* @see #openFileOutput
*/
public static final int MODE_APPEND = 0x8000;
如果我们不希望别人修改,访问你的数据
Context.MODE_PRIVATE
如果我们希望每次存取数据 都是以追加方式
Context.MODE_APPEND
默认文件的访问修饰权限 是私有
在linux下的文件访问权限是这样的,
第一个是, - 代表文件,d 代表目录
- | rw- | rw- | ---
当前用户 用户组 其他人
android的访问权限配置后,如下
以私有方式创建的文件 permissions -rw-rw----
全局可读 -rw-rw-r--
全局可写 -rw-rw--w-
全局可读写 -rw-rw-rw-
将文件储存有几种方式,存于ROM中,sdcard中,数据库中,SharedPreferences
存储于ROM中, FileOutputStream fos=context.openFileOutput(name, Context.MODE_PRIVATE);//name为文件路径
fos.write(content.getBytes());
fos.close();
读取ROM中的文件:FileInputStream fis=context.openFileInput(name);
int len=0;
byte b[]=new byte[1024];
while((len=fis.read(b))!=-1){
System.out.println(new String(b,0,len));
}
一些临时文件可以存储于cachedir中
File cacheDir = this.getCacheDir();程序的临时数据可以存放到这个目录,用户可以手工清除掉这个目录里面的内容
将文件存于SD卡的话,是要先对SD的状态进行判断的,示例代码如下
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))//判断SD卡知否正常挂载
File file=new File(Environment.getExternalStorageDirectory(),name);
FileOutputStream fos=new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
在android中使用的数据库是一个轻量级的关系型数据库,同时它还支持事务处理功能等等。sqlite 数据库 标准:要求我们数据库的主键 最好要以_id 作为名字
使用时我们要定义一个类来继承SQLiteOpenHelper,并重写他的构造函数和oncreate,onupgrade等方法。
构造函数中需要传递4个参数,分别为上下文对象,数据库名,数据工厂以及当前版本号,在oncreate方法中执行创建数据库的方法,若是数据库已经存在则要对比两者之间的版本号,本地版本低则要执行onupgrade方法,一致则不作任何操作。使用时只需要new出你的自定义类,通过SQLiteDatabase db=helper.getWritableDatabase();,来获取一个可读写的数据库,SQLiteDatabase db=helper.getReadableDatabase()是获取一个只读的数据库,进行增删查改的操作。查询操作返回的是一个Cursor对象,来操作取到的数据。
db.beginTransaction();
db.setTransactionSuccessful();
db.endTransaction();
这三条语句来控制事务的提交,1.打开数据库的事务。2.执行sql语句,3.设置事务的状态 (true),4.提交数据 true 提交数据 false 回滚数据
存储数据另外还用到得就是内容提供者,ContentProvider。
如果a应用想把自己的数据库暴露给别的应用程序使用,就必须实现contentprovider ,创建一个类 继承系统的ContentProvider,一定要在清单文件里面配置 ,指定uri的主机名 android:authorities=cn.itcast.db.personprovider
而继承后要重写全部的未实现方法,为了能够操作对应的uri,这里用到了UriMatcher来解析相关的uri,matcher.addURI("com.itheima.listview.content", "user", 1);这条语句来添加一个uri进来,后面加一个int只来判断不同的uri。