安卓常见存储及读取

一、sp存储 存储路径:/data/data/packageName/shared_prefs/yyy.xml

      (随软件删除而删除,未Root权限手机不能查看该路径)

     public class SpUtils {
        public static final String CACHE_URLS = "cache_urls";
        private static SharedPreferences sp;
        private static SpUtils instance;


        public static SpUtils getInstance(Context context) {
            if (instance == null) {
               sp = context.getSharedPreferences("xreal", Context.MODE_PRIVATE);
               instance = new SpUtils();
            }
            return instance;
        }
       /**
        * 保存数据
        *
        * @param name
        * @param value
        */
      public void save(String name, Object value) {
           if (value instanceof String) {
              sp.edit().putString(name, (String) value).apply();
           } else if (value instanceof Integer) {
              sp.edit().putInt(name, (Integer) value).apply();
           } else if (value instanceof Boolean) {
              sp.edit().putBoolean(name, (Boolean) value).apply();
           }
       }


       public int getInt(String name, int defValue) {
          return sp.getInt(name, defValue);
       }


       public String getString(String name, String defValue) {
         return sp.getString(name, defValue);
       }


       public boolean getBoolean(String name, Boolean defValue) {
         return sp.getBoolean(name, defValue);
       }
    }

二、内部存储:存储路径: /data/data/projectPackage/files/
      (随软件删除而删除,未Root权限手机不能查看该路径)

      读取文件
      FileInputStream fis = openFileInput("logo.png");
      保存文件
      FileOutputStream fos = openFileOutput("logo.png", MODE_PRIVATE)
      得到files文件夹对象
      File filesDir = getFilesDir();  
      操作asserts下的文件
      得到AssetManager : context.getAssets();
      读取文件: InputStream open(filename);
      加载图片文件
      Bitmap BitmapFactory.decodeFile(String pathName)   // .bmp/.png/.jpg


三、内存卡存储(外部存储) 操作权限:android.permission.WRITE_EXTERNAL_STORAGE
   1、不随软件删除而删除! 存储路径: /storage/sdcard/xxx/

       public String getSaveDirectory() {
          if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
              String rootDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "ScreenRecord" + "/";
              File file = new File(rootDir);
              if (!file.exists()) {
                  if (!file.mkdirs()) {
                    return null;
                  }
              }
              return rootDir;
          } else {
             return null;
          }
       }
  2、随软件删除而删除! 存储路径:/storage/sdcard/Android/data/packageName/files/
      public static String getResourceRootPath(Context mAppContext) {
         return mAppContext.getExternalFilesDir("VideoCache").getAbsolutePath() + File.separator;
      }


四、安卓下载内容到指定目录存储:

        private void startCacheVideo(final String downloadMovieName, final String downloadStingUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileOutputStream out = null;
                InputStream is = null;
                try {
                    String cacheUrl = downloadStingUrl;
                    URL url = new URL(cacheUrl);
                    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
                    String localUrl = Constants.getResourceRootPath(VideoCacheService.this)+ downloadMovieName;
                    File cacheFile = new File(localUrl);
                    out = new FileOutputStream(cacheFile,true);
                    is = httpConnection.getInputStream();
                    int mTotalSize = is.available();
                    int mCurrentSize = 0;
                    byte buf[] = new byte[4 * 1024];
                    int len = 0;
                    Intent mDownloadData = new Intent();
                    mDownloadData.setAction("xreal.recelerviewtest.service.VideoCacheService");
                    while ((len = is.read(buf)) != -1) {
                        try {
                            out.write(buf, 0, len);
                            mCurrentSize += len;
                            mDownloadData.putExtra("totalSize",mTotalSize);
                            mDownloadData.putExtra("currentSize",mCurrentSize);
                            sendBroadcast(mDownloadData);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

    }

五、读取文件

  public String loadFile2String(String fileName) {
        StringBuffer strBuffer = new StringBuffer();
        try {
            InputStream inputStream = new FileInputStream(fileName);
            InputStreamReader inputReader = new InputStreamReader(inputStream);
            BufferedReader bufferReader = new BufferedReader(inputReader);


            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                strBuffer.append(line);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }


        return strBuffer.toString();
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值