Android【File文件存储工具类】

Android【File文件存储工具类】

最近写项目用到了文件存储,当需要频繁的存储操作的时候,文件存储性能方面远大于SharedPreferences 。

工具类复制可用

public class FileUtils {
   

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
   
        //生成文件夹之后,再生成文件,不然会出错
        makeFilePath(filePath, fileName);
        String strFilePath = filePath + fileName;
        // 每次写入时,都换行写
        String strContent = strcontent + "\n";
        try {
   
            File file = new File(strFilePath);
            if (!file.exists()) {
   
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
   
            ToastUtils.show("请检查存储权限");
        }
    }

    //生成文件
    public static File makeFilePath(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;
    }

    //生成文件夹
    public static void makeRootDirectory(String filePath) {
   
        File file = null;
        try {
   
            file = new File(filePath);
            if (!file.exists()) {
   
                file.mkdir();
            }
        } catch (Exception e) {
   
            Log.i("error:", e + "");
        }
    }

    //读取指定目录下的所有TXT文件的文件内容
    public static String getFileContent(File file) {
   
        String content = "";
        if (!file.isDirectory()) {
     //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt")) {
   //文件格式为""文件
                try {
   
                    InputStream instream = new FileInputStream(file);
                    if (instream != null) {
   
                        InputStreamReader inputreader
                                = new InputStreamReader(instream, "UTF-8");
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line = "";
                        //分行读取
                        while ((line = buffreader.readLine()) != null) {
   
                            content += line + "";
                        }
                        instream.close();//关闭输入流
                    }
                } catch (java.io.FileNotFoundException e) {
   
                    Log.d("TestFile", "The File doesn't not exist.");
                } catch (IOException e) {
   
                    Log.d("TestFile", e.getMessage());
                }
            }
        }
        return content;
    }

    public static void DeleteFile(String path) {
   
        File file = new File(path);
        if (file.exists()) {
   
            file.deleteOnExit();
        }
    }

    public static void updateText(String strcontent, String filePath, String fileName) {
   
        makeFilePath(filePath, fileName);
        String strFilePath = filePath + fileName;
        String strContent = strcontent;
        try {
   
            File file = new File(strFilePath);
            if (!file.exists()) {
   
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            //写入的txt文档的路径
            PrintWriter pw = new PrintWriter(strFilePath);
            //写入的内容
            pw.write(strContent);
            pw.flush();
            pw.close();
        } catch (Exception e) {
   
            ToastUtils.show("请检查存储权限");
        }
    }

    /** * 读取changedata请求的id * @return 请求的id */
    public static String getXctId() {
   
        String id = getFileContent(new File("/sdcard/xct/id.txt"));
        return TextUtils.isEmpty(id) ? "0" : id;
    }

    /** * 保存changedata的id * @param id */
    public static void saveId(String id) {
   
        updateText(id, "/sdcard/xct/", "id.txt");
    }

    /** * 保存广告 * @param advertStr */
    public static void saveAdvert(String advertStr){
   
        updateText(advertStr, "/sdcard/xct/", "advert.txt");
    }

    /** * 读取广告数据 * @return */
    public static String getAdvert() {
   
        String advert = getFileContent(new File("/sdcard/xct/advert.txt"));
        return advert==null? "":advert;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/2813.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • k8s 很多pod evicted状态

    k8s 很多pod evicted状态k8s许多pod出现evicted状态。evicted状态是pod被驱逐无法起来问题原因:资源问题,资源不够解决办法:删除一些没用的大文件,然后将pod删除重建kubectlgetpods-ningress-nginx|awk‘{print$1}’|xargskubectldeletepods-ningress-nginxkubectlgetpods|grepEvicted|awk‘{print$1}’|xargskubectldelet

    2022年5月17日
    54
  • Linux 内核编程总结[通俗易懂]

    Linux 内核编程总结[通俗易懂]Linux内核编程总结   从事了几年的内核编程,对内核编程有一定的经验,现总结、吐槽下,作为标记。   任何进程都有有进程的入口点,用户态的进程,其入口点是,main函数。   那么内核的入口点是什么?个人理解整个OS,运行起来就是一个进程,   内核的入口点是init进程,在这个进程中负责:   1)子进程的创建,包括内核的线程、用户态的进程。

    2022年10月8日
    2
  • Java设计模式之行为型:备忘录模式

    Java设计模式之行为型:备忘录模式

    2021年10月4日
    42
  • spel表达式的用法_el表达式判断是否为空

    spel表达式的用法_el表达式判断是否为空spel表达式运算使用翻看公司代码,这一块不是很懂,查资料,记一下,还是太菜1.常用的对象Expression:表达式对象SpelExpressionParser:表达式解析器EvaluationContext:上下文2.使用本文参考了下面的几篇文章https://www.cnblogs.com/shihuc/p/9338173.htmlhttps://blog.csdn.net/f641385712/article/details/90812967下面的例子主要是来源于第一

    2025年9月6日
    5
  • c++线程间通信_c语言两个线程如何通信

    c++线程间通信_c语言两个线程如何通信c++线程间通过PostThreadMessage和GetMessage函数进行通信,下面用代码演示两个线程间的通信://ConsoleApplication1.cpp:定义控制台应用程序的入口点。//#include<stdio.h>#include<windows.h>usingnamespacestd;DWORDWINAPIThreadFun1(LPVOIDparam);DWORDWINAPIThreadFun2(LPVOIDpara

    2022年10月6日
    2
  • sudo与sudoers

    sudo与sudoerssudo是linux下常用的允许普通用户使用超级用户权限的工具,允许系统管理员让普通用户执行一些或者全部的root命令,如halt,reboot,su等等。这样不仅减少了root用户的登陆和管理时间,同样也提高了安全性。Sudo不是对shell的一个代替,它是面向每个命令的。它的特性主要有这样几点:  §sudo能够限制用户只在某台主机上运行某些命令。  §sudo提供了丰富

    2022年6月20日
    37

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号