Android保存字符串到本地储存卡中saveLocal

public class SaveLocal {
    //保存文件到sd卡
    public static void saveToFile(String content) {

        BufferedWriter out = null;
        //获取SD卡状态
        String state = Environment.getExternalStorageState();
        //判断SD卡是否就绪
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            //Toast.makeText(context, "请检查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(context, "保存成功", Toast.LENGTH_SHORT).show();

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

 

posted @ 2024-04-26 16:34  野生野鸡码农  阅读(3)  评论(0编辑  收藏  举报