Android中对字符串写入、读取、删除文件等操作

对文件的写入操作

参数 1.fileName文件的名称 2.msg文本信息

  1. 获得文件储存路径
 public static void init(String fileName) {
        logPath = getFilePath() + "/Logs";//获得文件储存路径,在后面加"/Logs"建立子文件夹
        mFlieName = logPath + fileName;//log日志名,使用时间命名,保证不重复
        File path = new File(logPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        try {

            File file = new File(mFlieName);
            if (mFlieName.contains(getDate())) {
                if (file.exists()) {
                    FileWriter fileWriter = new FileWriter(file, true);
                    fileWriter.write("");
                    fileWriter.flush();
                    fileWriter.close();
                }
            } else {
                if (file.exists()) {
                    FileWriter fileWriter = new FileWriter(file);
                    fileWriter.write("");
                    fileWriter.flush();
                    fileWriter.close();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2.获得文件存储路径

  /**
     * 获得文件存储路径
     */
    private static String getFilePath() {

        if (Environment.MEDIA_MOUNTED.equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {//如果外部储存可用
            return Config.appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
        } else {
            return Config.appContext.getFilesDir().getPath();//直接存在/data/data里,非root手机是看不到的
        }
    }

3.将信息写入文件中

public static String writeToFile(String fileName, String msg) {
        init(fileName);
        LogUtils.d("测试写入地址" + logPath);
        if (null == logPath) {
            LogUtils.e("logPath == null ,未初始化写入文件");
            return "fail";
        } else {
            String log = " " + msg + "\n";//内容,可以自行定制

            FileOutputStream fos;//FileOutputStream会自动调用底层的close()方法,不用关闭
            BufferedWriter bw = null;
            try {
                fos = new FileOutputStream(mFlieName, true);//这里的第二个参数代表追加还是覆盖,true为追加,flase为覆盖
                bw = new BufferedWriter(new OutputStreamWriter(fos));
                bw.write(log);
                return "success";
            } catch (Exception e) {
                e.printStackTrace();
                return "fail";
            } finally {
                try {
                    if (bw != null) {
                        bw.close();//关闭缓冲流
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

4.文件路径命名时获取当前日期

 /**
     * 返回当前日期
     */
    public static String getDate() {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        return formatter.format(curDate);
    }

以上是对文件的写入,下面将要读取刚才写入的文件

    /*
     * 读取文件
     *
     * */
    public static String readToFile(String strFilePath) {
        StringBuffer sb = new StringBuffer("");
        //打开文件
        File file = new File(strFilePath);
        //如果path是传递过来的参数,做非目录的判断
        if (file.isDirectory()) {
            LogUtils.d("The File doesn't not exist.");
            return "";
        } else {
            try {
                FileInputStream inputStream = new FileInputStream(file);
                if (inputStream != null) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    //创建字符缓冲流

                    String line;
                    //分行读取
                    while ((line = bufferedReader.readLine()) != null) {
                        //添加到字符缓冲流中
                        sb.append(line);
                        //一条一行
                        sb.append("\n");
                    }
                    inputStream.close();

                }
            } catch (java.io.FileNotFoundException e) {
                LogUtils.d("TestFile" + "The File doesn't not exist.");
            } catch (IOException e) {
                LogUtils.d("TestFile" + e.getMessage());
            }
        }
        return sb.toString();
    }

下面将要删除写入的文件

  /*
     * 删除文件
     * */
    public static String deleteToFile(String strFilePath) {
        LogUtils.d("测试删除" + strFilePath);
        File file = new File(strFilePath);
        if (file.isFile() && file.exists()) {
            file.delete();
            return "success删除成功";
        } else {
            return "fail 文件不存在";

        }

    }

记得加入相关权限!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值