FileCopeUtil 文件操作

作者: 颤抖的闪电 | 来源:发表于2018-01-23 10:59 被阅读45次

    前言:一直寻寻觅觅,就是找不到一个中意的文件操作类,加入我的知识体系,这个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;
            }
    
        }
    }
    

    相关文章

      网友评论

        本文标题:FileCopeUtil 文件操作

        本文链接:https://www.haomeiwen.com/subject/yutsaxtx.html