FileTools文件记录工具类

FileTools文件记录工具类

简介

1.用于记录特殊信息到指定文本
2.限制用于记录的文本大小,防止内容过大,处理方式为超过指定大小删除重建

所需权限

外置存储权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

代码

public class FileTools {
    private static String TAG = FileTools.class.getName();

    /**
     * 将字符串写入到文本文件中,如果文件大小超过限制,删除重建(用于做记录)
     */
    private static final long LIMIT_SIZE_1M = 1024 * 1024;
    private static final long LIMIT_SIZE_5M = 5 * 1024 * 1024;
    private static final String LOG_DIR = Environment.getExternalStorageDirectory().getAbsolutePath()+"/log_debug.txt";
    public static void writeToDebugFile(String strcontent) {
        Log.d(TAG, "writeToDebugFile: LOG_DIR:"+LOG_DIR);
        File file = makeFile(LOG_DIR);
        String strContent = "";
        try {
            if (getFileSize(file) > LIMIT_SIZE_5M) {
                if (file.delete()) {
                    file = makeFile(LOG_DIR);
                    strContent = "create at : " + getCurrentTime()+"\n";
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "writeTxtToFileAndLimitSize: 获取文件大小失败");
        }
        strContent = strContent + getCurrentTime() + "  " + strcontent + "\r\n";
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e(TAG, "文件写入失败:" + e);
        }
    }

    /**
     * 将字符串写入到文本文件中
     */
    public void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后,再生成文件,不然会出错
        File file = makeFile(filePath, fileName);
        // 每次写入时,都换行写
        String strContent = strcontent + "\r\n";
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e(TAG, "Error on write File:" + e);
        }
    }

    /**
     * 生成文件
     */
    public static File makeFile(String fileDir) {
        File file = new File(fileDir);
        try {
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 生成文件
     */
    private File makeFile(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 生成文件夹
     */
    private static void makeRootDirectory(String filePath) {
        File file;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            Log.i(TAG, "生成文件夹失败" + e);
        }
    }

    /**
     * 删除文件
     */
    public static void deleteFile(File file) {
        if (file.exists()) {
            if (file.delete()) {
                Log.d(TAG, "deleteFile: ok");
            } else {
                Log.e(TAG, "deleteFile: 文件删除失败");
            }
        } else {
            Log.e(TAG, "deleteFile: 无此文件");
        }

    }

    /**
     * 获取指定文件大小   
     */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 获取指定文件夹大小
     */
    public static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }

    /**
     * 转换文件大小
     */
    public static String toFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString;
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    private static String getCurrentTime() {
        Date mDate = new Date();
//        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH);
//        mDateStr = dateFormat.format(mDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.CHINA);
        return dateFormat.format(mDate);
    }
}

使用

FileTools.writeToDebugFile("这是一条文件记录");

结果

通过导出外部存储路径下下的文件查看记录
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值