欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android studio 将字符串写入本地的操作方法

时间:2021-01-10 11:07:02|栏目:Android代码|点击:

File 类的操作:

1.首先需要添加相关权限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

注意6.0以上需要动态申请:

private void checkPermission(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0以上
      int permission = ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.RECEIVE_SMS);
      int permission1 = ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
      if(permission != PackageManager.PERMISSION_GRANTED && permission1 != PackageManager.PERMISSION_GRANTED) {
        Log.e(TAG,"没有获取权限,请申请");
        // 申请一个(或多个)权限,并提供用于回调返回的获取码(用户定义)
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.RECEIVE_SMS) && ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {//这里可以写个对话框之类的项向用户解释为什么要申请权限,并在对话框的确认键后续再次申请权限
          Log.e(TAG,"提示");
          ActivityCompat.requestPermissions(this,
              new String[]{Manifest.permission.RECEIVE_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_READ_SMS);
        } else {
          //申请权限,字符串数组内是一个或多个要申请的权限,1是申请权限结果的返回参数,在onRequestPermissionsResult可以得知申请结果
          Log.e(TAG,"您已禁止");
          Toast.makeText(MainActivity.this,"没有获取读取手机权限,请到应用中心手动打开该权限",Toast.LENGTH_SHORT).show();
        }
      }else{
         Log.e(TAG,"获取到了权限");
      }
    }else{
      Log.e(TAG,"获取到了权限");
    }
  }
  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == CODE_READ_SMS){
      if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Log.e(TAG,"获取到了权限");
      } else{
        // 没有获取到权限,做特殊处理
        Log.e(TAG,"没有获取到权限");
        Toast.makeText(MainActivity.this,"没有获取读取手机权限,请到应用中心手动打开该权限",Toast.LENGTH_SHORT).show();
      }
    }
  }

2.saveToFile

a)BufferedWriter 追加

//保存文件到sd卡
  public void saveToFile(String content) {
    BufferedWriter out = null;

    //获取SD卡状态
    String state = Environment.getExternalStorageState();
    //判断SD卡是否就绪
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
      Toast.makeText(this, "请检查SD卡", Toast.LENGTH_SHORT).show();
      return;
    }
    //取得SD卡根目录
    File file = Environment.getExternalStorageDirectory();
    try {
      Log.e(TAG, "======SD卡根目录:" + file.getCanonicalPath());
      if(file.exists()){
        LOG.e(TAG, "file.getCanonicalPath() == " + file.getCanonicalPath());
      }
      /*
      输出流的构造参数1:可以是File对象 也可以是文件路径
      输出流的构造参数2:默认为False=>覆盖内容; true=>追加内容
       */
      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getCanonicalPath() + "/readMsg.txt",true)));
      out.newLine();
      out.write(content);
      Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

b)FileWriter追加

 /**
   * 使用FileWriter进行文本内容的追加
   * @param file
   * @param content
   */
  private void addTxtToFileWrite(File file, String content){
    FileWriter writer = null;
    try {
      //FileWriter(file, true),第二个参数为true是追加内容,false是覆盖
      writer = new FileWriter(file, true);
      writer.write("\r\n");//换行
      writer.write(content);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if(writer != null){
          writer.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

3.readFromFile()

//从SD卡读取文件
  public String readFromFile() {
    //读的时候要用字符流  万一里面有中文
    BufferedReader reader = null;
    FileInputStream fis;
    StringBuilder sbd = new StringBuilder();
    String state = Environment.getExternalStorageState();
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
      Toast.makeText(this, "SD卡未就绪", Toast.LENGTH_SHORT).show();
      return "";
    }
    File root = Environment.getExternalStorageDirectory();
    try {
      fis = new FileInputStream(root + "/readMsg.txt");
      reader = new BufferedReader(new InputStreamReader(fis));
      String row;
      while ((row = reader.readLine()) != null) {
        sbd.append(row);
      }
    } catch (FileNotFoundException e) {
      Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
      //e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return sbd.toString();
  }

4.removeFromFile()

//删除SD卡文件
  public void removeFromFile() {
    String state = Environment.getExternalStorageState();
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
      Toast.makeText(this, "SD卡未就绪", Toast.LENGTH_SHORT).show();
      return;
    }
    //取得SD卡根目录
    File root = Environment.getExternalStorageDirectory();
    File myFile=new File(root+"/sd.txt");
    //File myFile=new File(root,"sd.txt");
    if (myFile.exists()) {
      myFile.delete();
      Toast.makeText(this,"文件已删除",Toast.LENGTH_SHORT).show();
    }else {
      Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
    }
  }
}

总结

上一篇:Android 自动化测试经验分享 UiObejct.getFromParent()的使用方法

栏    目:Android代码

下一篇:Android TextView 去掉自适应默认的fontpadding的实现方法

本文标题:Android studio 将字符串写入本地的操作方法

本文地址:http://www.codeinn.net/misctech/43283.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有