android中文件操作的简单工具类

在开发过程中,我们经常会使用把一些信息保存到本地的内存当中,今天小编就给大家展示一个简单的文件操作的工具类,后续将会继续完善。废话不多少说,我们直接看代码。

public class FileUtils {

    private static final String mLogPath = "/utils/files";

    //创建文件
    public static void createFile(String name) {
        File file = new File(Environment.getExternalStorageDirectory() + mLogPath);
        try {
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(Environment.getExternalStorageDirectory() + mLogPath + "/" + name);
            if (!isLogExist(file)) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addLog(String fileName, String conent) {
        createFile(fileName + ".txt");
        fileName = Environment.getExternalStorageDirectory() + mLogPath + "/" + fileName + ".txt";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(fileName, true)));
            out.write(str+conent + "\r\n".getBytes("gbk"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 检查文件是否存在
     *
     * @param file
     * @return
     */
    private static boolean isLogExist(File file) {
        File tempFile = new File(Environment.getExternalStorageDirectory() + mLogPath);
        File[] files = tempFile.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                if (files[0].getName().trim().equalsIgnoreCase(file.getName())) {
                    return true;
                }
            }
        }

        return false;
    }

    //获取所有文件夹的名字
    public static String[] getFileName(String path) {
        File file = new File(path);
        String[] fileName = file.list();
        return fileName;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值