FileCopeUtil 文件操作

前言:一直寻寻觅觅,就是找不到一个中意的文件操作类,这个FileCopeUtil是我从E中整理出来的,先这样用着呗!算是比较实用的,慢慢完善呗!!!

/**
 * @desc 从FileCopeTool中整理过过来
 * @auth 方毅超
 * @time 2017/12/6 9:59
 */

public class FileCopeUtil {
    private FileCopeUtil() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 读取内存卡某路径的文件
     * 使用:String results = tool.readerFile(URL.HtmlBasePath, "Cube.json");
     *
     * @param path
     * @param fileName 带后缀
     * @return
     */
    public static String readerFile(String path, String fileName) {
        String result = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File s = new File(path + "/" + fileName);
            try {
                FileInputStream in = new FileInputStream(s);
                // 获取文件的字节数
                int lenght = in.available();
                // 创建byte数组
                byte[] buffer = new byte[lenght];
                // 将文件中的数据读到byte数组中
                in.read(buffer);
                result = new String(buffer, "UTF-8");
//                result = EncodingUtils.getString(buffer, "UTF-8");

            } catch (Exception e) {
            }
        }
        return result;
    }

    /**
     * path路径下的fileName文件,将字符串内容json写入
     * 使用:tool.writeToJsonFile("Cube", URL.HtmlBasePath + "/", json);json为String类型
     *
     * @param fileName
     * @param path
     * @param json
     * @return
     */
    public static boolean writeToJsonFile(String fileName, String path, String json) {
        Boolean flag = false;
        // 获取sd卡目录
        File file = null;
        OutputStream output = null;
        try {
            file = new File(path);
            if (!file.exists()) {
                file.mkdirs(); // 创建文件夹
            }
            file = new File(path + fileName + ".json");
            output = new FileOutputStream(file);
            output.write(json.getBytes());
            output.flush();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 判断SD里某路径的文件是否存在。
     * @param path
     * @param fileName 带后缀
     * @return
     */
    public static boolean isfileExist(String path, String fileName) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File s = new File(path + "/" + fileName);
            if (s.exists()) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 删除SD卡某路径下的某个文件
     * tool.deleteFile(URL.HtmlBasePath + "/" + identify + ".zip");
     *
     * @param path 路径+文件名
     */
    public static void deleteFile(String path) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File s = new File(path);
            s.delete();
        }
    }

    /**
     * 删除整个文件夹
     * FileCopeTool.deleteFolder(URL.HtmlPath + "/" + identify);
     *
     * @param path 路径,无需文件名
     */
    public static void deleteFolder(String path) {
        File f = new File(path);
        if (f.exists()) {
            // LogUtil.d("com.csair.ehome","存在该文件夹");
            // 在判断它是不是一个目录
            if (f.isDirectory()) {
                // LogUtil.d("com.csair.ehome","该文件夹是一个目录");
                // 列出该文件夹下的所有内容
                String[] fileList = f.list();
                if (fileList == null) {
                    return;
                }
                for (int i = 0; i < fileList.length; i++) {
                    // 对每个文件名进行判断
                    // 如果是文件夹 那么就循环deleteFolder
                    // 如果不是,直接删除文件
                    String name = path + File.separator + fileList[i];
                    File ff = new File(name);
                    if (ff.isDirectory()) {
                        deleteFolder(name);
                    } else {
                        ff.delete();
                    }
                }
                // 最后删除文件夹
                f.delete();

            } else {

                LogUtil.d("com.csair.ehome", "该文件夹不是一个目录");
            }
        } else {
            LogUtil.d("com.csair.ehome", "不存在该文件夹");
        }
    }

    /**
     * 在内存卡新建一个文件夹
     * @param dirPath       路劲
     * @param folderName    文件夹名
     */
    public static void createFile(String dirPath, String folderName) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File f = new File(dirPath + File.separator + folderName);
            if (!f.exists()) {
                LogUtil.d("com.csair.ehome", "文件夹不存在");
                f.mkdirs();
            }
        }
    }

    /**
     * 复制文件
     * @param sourceFile
     * @param targetFile
     * @throws IOException
     */
    public static void copyFile(File sourceFile, File targetFile)
            throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }

    /**
     * 往file中写入str
     * FileCopeTool.writeString(path, outputStr,1);
     * @param file
     *            :路径+文件名
     * @param str
     *            :内容
     * @param mode :0:create;1:overwrite
     */
    public static int writeString(String file, String str, int mode) {
        java.io.File outputFile = new java.io.File(file);
        if (outputFile.exists() && mode == 0) {
            return -1;
        }
        java.io.PrintWriter output;
        try {
            output = new java.io.PrintWriter(outputFile);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            return -2;
        }
        output.print(str);
        output.close();
        return 0;
    }

    /**
     * String inputStr = FileCopeTool.readString(path);
     * @param file 路径+文件名
     * @return
     */
    public static String readString(String file) {
//      String inputStr = "";
        StringBuffer inputStr = new StringBuffer();
        java.io.File inputFile = new java.io.File(file);
        java.util.Scanner input;
        try {
            input = new java.util.Scanner(inputFile);
            while (input.hasNext()) {
//              inputStr += input.next();
                inputStr.append(input.next());
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        input.close();
        return inputStr.toString();
    }


    /**
     * 获得指定文件的byte数组
     * @param filePath    路径+文件名
     * @return
     */
    public static byte[] readBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 根据byte数组,生成文件
     * @param filePath    路径+文件名
     * @param bfile
     */
    public static void writeBytes(String filePath, byte[] bfile) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }


    /**
     * 加密
     * @param path 路径+文件名
     * @param encAlgKey
     */
    public static void encrypt(String path, String encAlgKey) {
        String inputStr = readString(path);
        byte[] outputBytes = null;
        try {

            outputBytes = SymEncrypt.encrypt(inputStr, encAlgKey);
            writeBytes(path, outputBytes);
            Log.v("encrypt", "加密已完成");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("encrypt", "文件写入出错");
        }

    }

    /**
     * 解密
     * @param path 路径+文件名
     * @param strKey
     */
    public static void decrypt(String path, String strKey) {
        byte[] inputBytes = readBytes(path);
        String outputStr = null;
        try {
            outputStr = SymEncrypt.decrypt(inputBytes, strKey);
            writeString(path, outputStr, 1);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("decrypt", "文件写入出错");
            return;
        }
        if (outputStr == null) {
            Log.e("decrypt", "文件写入出错");
            return;
        }
        Log.v("decrypt", "解密完成");

    }

    /**
     * 加密类,从SymEncrypt中复制而来
     */
    public static class SymEncrypt {

        public static Key getKey(byte[] arrBTmp, String alg) {
            byte[] arrB = new byte[8];
            int i = 0;
            int j = 0;
            while (i < arrB.length) {
                if (j > arrBTmp.length - 1) {
                    j = 0;
                }
                arrB[i] = arrBTmp[j];
                i++;
                j++;
            }
            Key key = new javax.crypto.spec.SecretKeySpec(arrB, alg);
            return key;
        }

        public static byte[] encrypt(String s, String strKey) {
            byte[] r = null;
            try {
                Key key = getKey(strKey.getBytes(), "DES");
                Cipher c;
                c = Cipher.getInstance("DES");
                c.init(Cipher.ENCRYPT_MODE, key);
                r = c.doFinal(s.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return r;
        }

        public static String decrypt(byte[] code, String strKey) {
            String r = null;
            try {
                Key key = getKey(strKey.getBytes(), "DES");
                Cipher c;
                c = Cipher.getInstance("DES");
                c.init(Cipher.DECRYPT_MODE, key);
                byte[] clearByte = c.doFinal(code);
                r = new String(clearByte);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return r;
        }

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • ——· 关于本书和作者 ·—— 本书的作者是凯利·麦格尼格尔,他是斯坦福大学医学健康促进项目的一名健康心理学家和教...
    玲玲A阅读 522评论 0 0
  • 现在说起来,应该是两年前看过的一个片子了。因为是中间调台过去的,所以也不知道片子叫什么名字。韩国的一部电影,应该不...
    滕帆Fun阅读 366评论 1 2
  • 02 三天的期限还没到,单磊磊就又跑过来问我,木子,我是真的喜欢你,求你答应我吧!我红着脸说:我还没想好呢!然后跑...
    小小圣女果阅读 227评论 0 1
  • 2017年10月17号,星期二,阴,今天
    wz_9f5e阅读 61评论 0 0
  • 有人问我,喜欢一个不喜欢你的人累吗? 是不是整个宇宙都想看看我爱你能坚持多久?我也不知道我能坚持多久,也不想硬要拿...
    怪喵Miao阅读 3,998评论 0 1