Android --- 文件的创建、写入、读取、压缩操作示例代码

import android.content.Context;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtils {
    private static String LOCAL_FILE_PATH;
    private static FileUtils fileUtils;
    private static Context context;
    private Object lock;

    // 私有构造
    private FileUtils() {
    }

    // 单例
    public static FileUtils getInstance() {
        if (null == fileUtils) {
            fileUtils = new FileUtils();
        }
        return fileUtils;
    }

    // 首先调用 init() 函数
    public void init(Context mContext) {
        context = mContext;
        lock = new Object();
        LOCAL_FILE_PATH = context.getFilesDir().getPath() + "/";
    }

    // 创建文件
    public void create(String name) {
        // 判断文件夹是否有了
        File fileDirectory = new File(LOCAL_FILE_PATH);
        if (!fileDirectory.exists()) {
            fileDirectory.mkdirs();
        }
        // 判断是否有这个文件
        File file = new File(context.getFilesDir().getPath() + "/" + name);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 写入文件
     * name : 文件名字
     * str:写入的字符串
     */
    public void write(String name, String str) {
        synchronized (lock) {
            // 判断文件夹是否有了
            File fileDirectory = new File(LOCAL_FILE_PATH);
            if (!fileDirectory.exists()) {
                fileDirectory.mkdirs();
            }
            // 判断是否有这个文件
            File file = new File(context.getFilesDir().getPath() + "/" + name);
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(file, true); // true 代表写完一条接着写,反之清空之前的数据再写入
                if (null != fileOutputStream) {
                    fileOutputStream.write(str.getBytes());
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            } finally {
                try {
                    if (null != fileOutputStream) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println(e.getMessage());
                }
            }
        }
    }


    /**
     * 读取文件
     * name : 文件名字
     */
    public String read(String name) {
        File fileDirectory = new File(LOCAL_FILE_PATH);
        if (!fileDirectory.exists()) {
            fileDirectory.mkdirs();
        }
        // 判断是否有这个文件
        File file = new File(context.getFilesDir().getPath() + "/" + name);
        FileInputStream inputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = new StringBuilder();

        if (file.exists()) {
            try {
                inputStream = context.openFileInput(name);
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                while (null != (line = bufferedReader.readLine())) {
                    stringBuilder.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            } finally {
                try {
                    if (null != bufferedReader) {
                        bufferedReader.close();
                    }
                    if (null != inputStream) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 文件的压缩
     * 1.compressFilePath:要压缩文件的路径
     * 2.name:要压缩文件的名字
     * 3.toLocalPath:把文件压缩到哪里
     */
    public void compress(String compressFilePath, String name, String toLocalPath) throws IOException {
        Boolean isCompress = false;
        File file = new File(compressFilePath); // 判断要压缩的文件路径是否存在
        File compress = new File(toLocalPath); // 判断你压缩后的文件路径是否存在

        if (!compress.exists()) {
            compress.mkdirs();
        }

        // 压缩前的文件可能是.txt 文件,我们根据点来分割提取点之前的部分
        String str[] = name.split("\\.");
        String compressName = str[0] + ".zip";

        // 对文件压缩前进行判断,这个文件之前是否已经被压缩过
        File[] files = compress.listFiles();
        if (null != files) {
            for (File f : files) {
                if (f.getName().endsWith(compressName)) {
                    isCompress = true;
                }
            }
        }

        // 压缩处理
        if (!isCompress) {
            ZipOutputStream zipOutputStream = null;
            FileInputStream fileInputStream = null;
            try {
                zipOutputStream = new ZipOutputStream(new FileOutputStream(toLocalPath + compressName));
                if (null != zipOutputStream) {
                    if (file.isFile()) {
                        ZipEntry zipEntry = new ZipEntry(name);
                        fileInputStream = new FileInputStream(file);
                        zipOutputStream.putNextEntry(zipEntry);
                        int len;
                        byte[] bytes = new byte[5000];
                        while ((len = fileInputStream.read(bytes)) != -1) {
                            zipOutputStream.write(bytes, 0, len);
                        }
                        zipOutputStream.closeEntry();
                    }
                } else {
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            } finally {
                if (null != zipOutputStream) {
                    zipOutputStream.close();
                }
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            }
        }

    }

}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁同学与Android

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值