zoukankan      html  css  js  c++  java
  • Android的数据存储

     Android支持四种数据存储方式,分别是Preference, File, DataBase, Content Provider 。这几天工作上的一个测试程序要求存储一个图像文件,用了用File的这种方式,有了一点小小的心得。

     

        先说下,Preference,File, DataBase这三种方式分别对应的目录是/data/data/Package Name/Shared_Pref, /data/data/Package Name/files, /data/data/Package Name/database 。

     

        在Android中通常使用File存储方式是用Context.openFileOutput(String fileName, int mode)和Context.openFileInput(String fileName)。

     

        Context.openFileOutput(String fileName, int mode)生成的文件自动存储在/data/data/Package Name/files目录下,其全路径是/data/data/Package Name/files/fileName 。注意下,这里的参数fileName不可以包含路径分割符(如"/")。

     

        通常来说,这种方式生成的文件只能在这个apk内访问。但这个结论是指使用Context.openFileInput(String fileName)的方式。使用这种方式,每个apk只可以访问自己的/data/data/Package Name/files目录下的文件,原因很简单,参数fileName中不可以包含路径分割符,Android会自动在/data/data/Package Name/files目录下寻找文件名为fileName的文件。

     

        但是如果你直接使用这个File,那么这个File在其它apk中也是可以访问的,不过要注意在之前调用Context.openFileOutput(String file, int mode)时不要使用缺省的mode:MODE_PRIVATE ,而应该使用MODE_WORLD_READABLE 。使用缺省mode生成的文件的权限是“660”(也就是rw-rw----),而使用后者生成文件的权限是允许运行别的apk访问的。代码如下:

         File file = new File("/data/data/Package Name/files/fileName");

     

        另外还有一个方法可以改变这个生成文件的权限。可以直接在Java代码中执行Linux命令,毕竟Android归根到底也是Linux .代码如下:

       // Process process = Runtime.getProcess().exec("chmod 666 /data/data/Package Name/files/fileName");
       //process.waitFor();

     Process process = Runtime.getRuntime().exec ("ls");      
              BufferedReader   ins   =   new   BufferedReader(new  InputStreamReader(process.getInputStream()));
              String line;
              while((line = ins.readLine())!=null)  
               {  
               Toast.makeText(this, line, Toast.LENGTH_LONG).show();
               }

  • 相关阅读:
    面试题6:用两个栈实现队列
    cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062: 解决办法
    支付系统的对账处理与设计--转
    centos 6.7下安装rabbitmq 3.6.6过程
    Can't access RabbitMQ web management interface after fresh install
    Spring Cloud Netflix Eureka client源码分析
    spring cloud config配置中心源码分析之注解@EnableConfigServer
    量化派基于Hadoop、Spark、Storm的大数据风控架构--转
    Inversion of Control Containers and the Dependency Injection pattern--Martin Fowler
    spark groupByKey 也是可以filter的
  • 原文地址:https://www.cnblogs.com/tt_mc/p/1705348.html
Copyright © 2011-2022 走看看