博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android 建立文件夹、生成文件并写入文本文件内容
阅读量:6926 次
发布时间:2019-06-27

本文共 1413 字,大约阅读时间需要 4 分钟。

hot3.png

  • 一、首先添加权限

     

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    二、建立文件夹、生成文件并写入文本文件内容代码
     
    private void initData() {
        String filePath = "/sdcard/Test/";
        String fileName = "log.txt";
        
        writeTxtToFile("txt content", filePath, fileName);
    }
     
    // 将字符串写入到文本文件中
    public void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后,再生成文件,不然会出错
        makeFilePath(filePath, fileName);
        
        String strFilePath = filePath+fileName;
        // 每次写入时,都换行写
        String strContent = strcontent + "\r\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) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }
     
    // 生成文件
    public 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+"");
        }

转载于:https://my.oschina.net/u/2489258/blog/671842

你可能感兴趣的文章
一个js下拉菜单 类似jq效果
查看>>
背景图片百分之百大小css设置方法
查看>>
Google Play和基于Feature的过滤 —— Feature 参考手册
查看>>
背包问题
查看>>
eclipse cdt Program "make" not found in PATH
查看>>
Redis命令拾遗四(集合类型)—包含简单搜索筛选商品设计实例。
查看>>
第二十九章 springboot + zipkin + mysql
查看>>
maven提示invalid LOC header (bad signature)的解决办法
查看>>
classloader example
查看>>
Python sockets - sending string in chunks of 10 bytes - Stack Overflow
查看>>
使用MQ要考虑的问题
查看>>
提升Android应用视觉效果的10个UI技巧【转】
查看>>
通过Tag标签回退版本修复bug
查看>>
TH文字编辑器开发的第一个游戏,唐伯虎泡妞
查看>>
程序员去创业公司做 CTO,需要注意什么?
查看>>
躺玩手机险些酿成大祸 你知道危害有多大吗?
查看>>
链家鸟哥:从留级打架问题学生到PHP大神,他的人生驱动力竟然是?|二叉树短视频...
查看>>
自动驾驶公司Momenta累计完成超2亿美金融资 腾讯等参与
查看>>
贾跃亭所持乐视网股权触及平仓线 部分面临被司法拍卖
查看>>
香港著名地标“星光大道”重开
查看>>