Android 数据存储之 File

优点:  1.适合游戏存储,能存储较大数据;
        2.不仅能存储到系统中,也能存储到SD卡中!
    
@保存方式:Stream 数据流方式
 * @注意1:默认情况下,使用openFileOutput 方法创建的文件只能被其调用的应用使用,
 *         其他应用无法读取这个文件,如果需要在不同的应用中共享数据;
 *
 * @注意2:因为android  os内部闪存有限,所以适合保存较少的数据,当然我们也有解决的方法,
 *         就是把数据保存在SD开中,这样就可以了!
 *
 * @提醒1 调用FileOutputStream 时指定的文件不存在,Android 会自动创建它。
 *        另外,在默认情况下,写入的时候会覆盖原 文件内容,如果想把新写入的内
 *        容附加到原文件内容后,则可以指定其mode为Context.MODE_APPEND。
 *          openFileInput("save.data")当指定的文件不存在时会抛出异常,所以代码部分需要捕获异常。
 *
 * @提醒2 这里我给大家讲两种方式,一种是原生态file流来写入/读入,
 *        另外一种是用Data流包装file流进行写入/读入 其实用data流来包装进行操作;
 *        原因是:包装后支持了更多的写入/读入操作,比如:file流写入不支持
 *        writeUTF(String str); 但是用Data包装后就会支持。
 *          最后在操作完后需要关闭所有的流
 *
 * @操作模式: Context.MODE_PRIVATE:新内容覆盖原内容
 *            Context.MODE_APPEND:新内容追加到原内容后
 *            Context.MODE_WORLD_READABLE:允许其他应用程序读取
 *            Context.MODE_WORLD_WRITEABLE:允许其他应用程序写入,会覆盖原数据。

 

--------------Android中单纯用file来读入的方式-----------------
//也可以通过File file = new File(文件路径);
//路径默认是/data/data/包/files下,主包名称可以查看AndroidManifest.xml的package,或者通过context.getFilesDir().getAbsolutePath()
FileInputStream fis = this.openFileInput("save.data"); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { byteArray.write(buffer, 0, len); } String temp = byteArray.toString(); --------------Android中用data流包装后的读入的方式----------------- FileInputStream fis = this.openFileInput("save.himi"); DataInputStream dis = new DataInputStream(fis); String temp = dis.readUTF(); //写出草SD卡是需要判断是否存在 Environment.getExternalStorageState() --------------Android中单纯用file来写入的方式-------------- FileOutputStream fos = new FileOutputStream(f); fos.write(str.getBytes()); --------------Android中data包装后来写入的方式-------------- FileOutputStream fos = this.openFileOutput("save.himi", MODE_PRIVATE); //注意:如果是系统路径,当没有此文件的时候,android 会默认创建一个!但是我们放入SD卡的时候要自己创建目录路径和文件! // if (Environment.getExternalStorageState() != null) {// 这个方法在试探终端是否有sdcard! // Log.v("Himi", "有SD卡"); // File path = new File("/sdcard/包名");// 创建目录 // File f = new File("/sdcard/包名/save.himi");// 创建文件 // if (!path.exists()) {// 目录不存在返回false // path.mkdirs();// 创建一个目录 // } // if (!f.exists()) {// 文件不存在返回false // f.createNewFile();// 创建一个文件 // } // fos = new FileOutputStream(f);// 将数据存入sd卡中 // } DataOutputStream dos = new DataOutputStream(fos); dos.writeUTF(str.toString()); //api规定当写入字符串的时候必须写入UTF-8格式的编码 //String content = EncodingUtils.getString(buffer, ”UTF-8″); 这个也能把字符数组转码制!

这里我们为什么要使用Data流来包装,其实不光是获得更多的操作方式,最主要的是方便快捷,你比如用file来读入的时候,明显的复杂了一些不说,它还一次性把所有数据都取出来了,不便于对数据的处理!
注意要在AndroidManifest.xml中添加SD卡读写权限<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>


原文地址:https://www.cnblogs.com/rfheh/p/4164786.html