文件存储之:File,Cache,Sdcard,三种存储方式

来源:互联网 发布:战地4破解软件 编辑:程序博客网 时间:2024/05/29 06:56
//canche存储数据,记得添加sdcard的读写权限File file = new File(getCacheDir(), "cache.text");try {    FileOutputStream fo = new FileOutputStream(file);    fo.write("这是cache存储的缓冲信息".getBytes());    fo.close();    Toast.makeText(MainActivity.this, "保存成功", 0).show();} catch (Exception e) {    e.printStackTrace();}//canche读取数据File file1 = new File(getCacheDir(), "cache.text");try {    FileInputStream fi = new FileInputStream(file1);    BufferedReader br = new BufferedReader(            new InputStreamReader(fi));    String readLine = br.readLine();    Toast.makeText(MainActivity.this, readLine, Toast.LENGTH_SHORT).show();    br.close();    fi.close();} catch (Exception e) {    e.printStackTrace();}
  //File存储文件  try {      FileOutputStream fi = openFileOutput("file.text",              MODE_PRIVATE);      fi.write("这是file格式存储的文件".getBytes());      fi.close();      Toast.makeText(MainActivity.this, "存储成功", 0).show();  } catch (Exception e) {      e.printStackTrace();  }//FIle读取文件  try {      FileInputStream fi = openFileInput("file.text");      BufferedReader br = new BufferedReader(              new InputStreamReader(fi));      String readLine = br.readLine();      br.close();      fi.close();      Toast.makeText(MainActivity.this, readLine, 0).show();  } catch (Exception e) {      e.printStackTrace();  }

        /**         * Environment.getExternalStorageState()检测sd卡是否存在         * Environment.getDataDirectory() 获取到机身内部存储的路劲         *  sdcard 存储数据         * 首先判断SD卡是否存在         */        if (Environment.getExternalStorageState().equals(                Environment.MEDIA_MOUNTED)) {//       得到系统路劲            File file = Environment.getExternalStorageDirectory();            String file2 = file.getAbsoluteFile() + "/putsdcard.text";            try {                FileOutputStream fo = new FileOutputStream(file2);                fo.write("这是保存在sdcard上的数据".getBytes());                fo.close();                Toast.makeText(MainActivity.this, "存储成功", Toast.LENGTH_SHORT).show();            } catch (Exception e) {                e.printStackTrace();            }        }    }    //sdcard读取数据    try {        File file = new File(Environment.getExternalStorageDirectory(),                "putsdcard.text");        FileInputStream fi = new FileInputStream(file);        BufferedReader br = new BufferedReader(                new InputStreamReader(fi));        String readLine = br.readLine();        br.close();        fi.close();        Toast.makeText(MainActivity.this, readLine, 0).show();    } catch (Exception e) {        e.printStackTrace();    }

原创粉丝点击