Android 中可以在设备的存储设备上创建用于保存数据的文件,也可以在外接的设备上创建用于保存数据的文件,在默认的情况下,文件Files不能在不同的程序间共享。
Files文件的数据存储主要是使用Properties 配合 FileInputStream或者FileOutputStream对文件写入操作。Properties对应的“键-值”必须是字符串形式的数据类型。Properties(属性),可以把Properties继承自Hashtable,理解成一个Hashtable。
Properties的重要方法如下详细说明:
- 方法:String getProperty(String name, String defaultValue)
解释:通过指定的 “name“ 即Key,搜索属性,参数二为默认值,即通过Key找不到文件中的属性时,要返回的默认值。
- 方法:String getProperty(String name)
解释:通过指定的 ”name“ 即为 Key,搜索属性,没有返回默认值。
- 方法:void list(PrintStream out)
解释:通过PrintStream 列出可读的属性列表
- 方法:void list(PrintWriter writer)
解释:通过PrintStream 列出可写的属性列表
- 方法:synchronized void load(InputStream in)
解释:从指定的 ”inputStream “ 即输出流,加载properties
- 方法:synchronized void loadFromXML(InputStream in)
解释:从指定的 "InputStream" 即输出流,加载一个以XML形式的 Properties
- 方法:Enumeration <?> propertyNames()
解释:返回所有包含在文件里面的属性名称
- 方法:void save(OutputStream out, String comment)
解释:注意,这种保存方法己经过时,Google 不推荐使用此种写法,这种方法忽略任何IO 异常,所以在实际操作过程中,可能会发生不必要的异常。
- 方法:object setProperty(String name, String value)
解释:设置属性,保存一个”键-值“对的属性。
- 方法:synchronized void store(OutputStream out, String comment)
解释:通过 FileOutputStream 打开对应的程序文件,然后通过Store 保存之前 Properties 打包好的数据。这里备注可以为空。
- 方法:void storeToXML(OutputStream os, String comment)
解释:通过FileOutputStream 打开对应的程序文件,将打包好的数据写入到XML文件。
- 方法:synchronized void storeToXML(OutputStream os, String comment, String encoding)
解释:通过FileOutputStream 打开对应的程序文件,将打包好的数据写入到XML文件,第三个参数可以指定编码。
下面是例子,后面会有详细的源码实例。
//构建Properties对象
Properties myProperties = new Properties();
//打开文件
FileInputSteam steam = this.opeFileInput("myFile.txt");
//读取文件内容
myProperties.load(stream);