Android文件读写工具类

记录使用
InputStream,OutputStream。

根据流所处理的数据类型分为两类:

  • 字节流:用于处理字节数据。(InputStream,OutputStream)
  • 字符流:用于处理字符数据,Unicode字符数据。(Reader,Writer)
RandomAccessFile
  • 支持对文件的读取和写入随机访问,比较灵活

  • 构造mode 有4种类型:
    r 只读
    rw 读写
    rwd 读写,并且文件内容在改变时会同步到磁盘
    rws 并且文件元数据或者文件内容在改变时会同步到磁盘

  • 5哈测试

 mPath = FileUtils.getRootPath()+ File.separator+"测试文件夹"+File.separator;
        mName = "哈哈哈哈哈.txt";
        mStr = "《哈哈哈哈哈》(全称:哈哈哈哈哈——很高兴遇到你)是爱奇艺、腾讯视频出品," +
                "浙江蓝天下传媒集团、橙子映像、浙江合心传媒联合出品的公路行进式户外真人秀,由邓超、" +
                "陈赫、鹿晗担任固定嘉宾。";
        checkPermissions();
        /*FileUtils.writeFileR(mStr,mPath,mName);

        String str = FileUtils.readFileR(mPath, mName);*/

        FileUtils.writeFileO(mStr,mPath,mName);
        
        String str = FileUtils.readFileI(mPath, mName);
public class FileUtils {
    private static String TAG = FileUtils.class.getSimpleName();

    /*
     * external storage
       外部存储	Environment.getExternalStorageDirectory()	SD根目录:/mnt/sdcard/ (6.0后写入需要用户授权)
                context.getExternalFilesDir(dir)	路径为:/mnt/sdcard/Android/data/< package name >/files/…
                context.getExternalCacheDir()	路径为:/mnt/sdcard//Android/data/< package name >/cach/…
                *
      internal storage
      内部存储
              context.getFilesDir()	路径是:/data/data/< package name >/files/…
              context.getCacheDir()	路径是:/data/data/< package name >/cach/…
    */

    /**
     * @return .外部储存sd卡 根路径
     */
    public static String getRootPath() {
        // /storage/emulated/0
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    /**
     * @param context .
     * @return . 外部储存sd卡 :/mnt/sdcard/Android/data/< package name >/files/…
     */
    public static String getAppRootPth(Context context) {
        // /storage/emulated/0/Android/data/pack_name/files
        return context.getExternalFilesDir("").getAbsolutePath();
    }

    /**
     * @return .内部存储
     */
    public static String getInternalPath() {
        // /data
        return Environment.getDataDirectory().getAbsolutePath();
    }

    /**
     * @param context .
     * @return .内部储存:/data/data/< package name >/files/
     */
    public static String getInternalAppPath(Context context) {
        return context.getFilesDir().getAbsolutePath();
    }


    /**
     * @param path     路径
     * @param fileName 文件名称
     * @return .
     */
    public static boolean createFile(String path, String fileName) {
        File file = new File(path + File.separator + fileName);

        //先创建文件夹 保证文件创建成功
        createDirs(path);

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        } else {
            //
            return false;
        }
    }

    /**
     * @param folder 创建多级文件夹
     * @return .
     */
    public static boolean createDirs(String folder) {
        File file = new File(folder);

        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            Log.i(TAG, "createDirs: 不存在文件夹 开始创建" + mkdirs + "--" + folder);
            return true;
        } else {
            Log.i(TAG, "createDirs: 文件夹已存在");
        }
        return false;
    }


    /**
     * =======================================文件读写=============================================
     *
     * @param content   写入字符串
     * @param path      .    目录
     * @param fileName  .文件名
     * @param isRewrite 是否覆盖
     */
    //1.RandomAccessFile 读写
    public static void writeFileR(String content, String path, String fileName, boolean isRewrite) {

        File file = new File(path + fileName);
        if (!file.exists()) {
            createFile(path, fileName);
        }

        RandomAccessFile randomAccessFile;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");

            if (isRewrite) {
                randomAccessFile.setLength(content.length());
                randomAccessFile.seek(0);
            } else {
                randomAccessFile.seek(randomAccessFile.length());
            }
            randomAccessFile.write(content.getBytes());

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

    public static void writeFileR(String content, String path, String fileName) {

        File file = new File(path + fileName);
        if (!file.exists()) {
            createFile(path, fileName);
        }

        RandomAccessFile randomAccessFile;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");
            //默认覆盖
            randomAccessFile.setLength(content.length());
            randomAccessFile.seek(0);

            randomAccessFile.write(content.getBytes());

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

    /**
     * 读文件
     *
     * @param path     .
     * @param fileName .
     * @return .
     */
    public static String readFileR(String path, String fileName) {
        File file = new File(path + fileName);
        if (!file.exists()) {
            Log.i(TAG, "readFileR: return null");
            return null;
        }
        StringBuilder buffer = new StringBuilder();
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

            randomAccessFile.seek(0);
            byte[] buf = new byte[(int) randomAccessFile.length()];
            if (randomAccessFile.read(buf) != -1) {
                buffer.append(new String(buf));
                Log.i(TAG, "readFileR: length" + randomAccessFile.length());
                //buffer.append(new String(buf, StandardCharsets.UTF_8));
            }
            randomAccessFile.close();
        } catch (IOException e) {
            Log.i(TAG, "readFileR: " + e.getMessage());
            e.printStackTrace();
        }

        return buffer.toString();
    }


    /**
     * 读文件
     *
     * @param path   .文件路径
     * @param name   .名称
     * @return .
     */
    public static String readFileI(String path, String name ) {
        //默认编码格式 StandardCharsets.UTF_8;
        File file = new File(path,name);
        if (!file.exists()) {
            return null;
        }
        StringBuilder builder = new StringBuilder("");
        try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),StandardCharsets.UTF_8 ));
        String line;

            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append("\n");
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();

    }


    /**
     * 写入文件
     *
     * @param content  内容.
     * @param path     目录.
     * @param fileName 文件名   .
     */
    public static void writeFileO(String content, String path, String fileName) {
        File file = new File(path + fileName);
        if (!file.exists()) {
            //文件目录不存在  先创建
            createFile(path, fileName);
        }
        try {

            FileOutputStream ops = new FileOutputStream(file, false);
            OutputStreamWriter opsw = new OutputStreamWriter(ops, StandardCharsets.UTF_8);
            // byte[] bytes = content.getBytes();
            opsw.write(content);
            opsw.close();

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

    /**
     * @param content   .
     * @param path      .
     * @param fileName  .
     * @param isReWrite .是否追加
     */
    public static void writeFileO(String content, String path, String fileName, boolean isReWrite) {
        File file = new File(path + fileName);
        if (!file.exists()) {
            //文件目录不存在  先创建
            createFile(path, fileName);
        }

        try {

            FileOutputStream ops = new FileOutputStream(file, isReWrite);
            OutputStreamWriter opsw = new OutputStreamWriter(ops, StandardCharsets.UTF_8);
            // byte[] bytes = content.getBytes();
            opsw.write(content);
            opsw.close();

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


}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值