FileUtils

作者: 河马过河 | 来源:发表于2020-03-19 18:21 被阅读0次
public class FileUtil {

    public static boolean hasStorage() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    public static boolean canSave(byte[] byteData) {
        if (byteData.length < getAvailaleSize()) {
            return true;
        }
        return false;
    }
  public static int getAvailaleSize() {
        File path = Environment.getExternalStorageDirectory(); 
        StatFs stat = new StatFs(path.getPath());
        int blockSize = stat.getBlockSize();
        int availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    public static boolean isExistFile(String strFile) {
        if (strFile == null || strFile.equals("")) {
            return false;
        }
        File f = new File(strFile);
        return f.exists();
    }

    public static void mkdir(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists() && dir.isDirectory()) {
            dir.mkdir();
        }
    }

    public static boolean mkdirs(String dirPath) {
        File dir = new File(dirPath);
        if (dir.exists() && dir.isFile()) {
            dir.delete();
        }

        if (!dir.exists()) {
            return dir.mkdirs();
        }

        return true;
    }

    public static boolean createFile(String path) {
        File f = new File(path);
        try {
            return f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
 public static void rename(String oldFilePath, String newFilePath) {
        File file = new File(oldFilePath);
        File newFile = new File(newFilePath);

        file.renameTo(newFile);
        file.delete();
    }
 public static boolean deleteAll(String filePath) {
        if (filePath == null) {
            return false;
        }

        File file = new File(filePath);

        return deleteAll(file);
    }

    public static boolean deleteAll(File file) {
        if (file == null) {
            return false;
        }

        if (file.isFile()) {
            return file.delete();
        }

        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                return file.delete();
            }

            for (int i = 0; i < childFiles.length; i++) {
                deleteAll(childFiles[i]);
            }
            return file.delete();
        }

        return false;
    }
  public static void writeToFile(String filePath, byte[] bytes, boolean append) {
        try {
            File file = new File(filePath);
            if (!file.isFile()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file, append);// openFileOutput(filePath,MODE_PRIVATE);
            fos.write(bytes);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 /**
     * 获取文件大小
     *
     * @param filePath 文件路径
     * @param isDel    是否删除无size文件
     * @return
     */
    public static long getFileSize(String filePath, boolean isDel) {
        if (filePath != null) {
            try {
                File file = new File(filePath);
                if (file.exists()) {
                    long size = getFileSize(file);
                    if (isDel && size <= 0) {
                        file.delete();
                    }
                    return size;
                } else {
                    return -1;
                }
            } catch (Exception e) {
                // TODO: handle exception
                return -2;
            }

        }

        return -3;
    }

    public static long getFileSize(String filePath) {
        return getFileSize(filePath, false);
    }
 public static long getFileSize(File f) throws Exception {
        if (f.isFile()) {
            return f.length();
        }
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }
  public static void getAllFilesFullPathList(ArrayList<String> fileList, String path) {
        LinkedList<File> list = new LinkedList<File>();
        File dir = new File(path);
        File file[] = dir.listFiles();
        if (file == null)
            return;
        for (int i = 0; i < file.length; i++) {
            if (file[i].isDirectory())
                list.add(file[i]);
            else {

                String strFileName = file[i].getAbsolutePath();
                // EsLog.i("VideoFileUtil", "fileFullName:" + strFileName);
                fileList.add(strFileName);
            }
        }
        File tmp;
        while (!list.isEmpty()) {
            tmp = list.removeFirst();// �׸�Ŀ¼
            if (tmp.isDirectory()) {
                file = tmp.listFiles();
                if (file == null)
                    continue;
                for (int i = 0; i < file.length; i++) {
                    if (file[i].isDirectory())
                        list.add(file[i]);
                    else {
                        String strFileName = file[i].getAbsolutePath();
                        // EsLog.i("VideoFileUtil", "fileFullName:" + strFileName);
                        fileList.add(strFileName);
                    }
                }
            } else {
                String strFileName = tmp.getAbsolutePath();
                // EsLog.i("VideoFileUtil", "fileFullName:" + strFileName);
                fileList.add(strFileName);
            }
        }
    }
  public static void getAllFilesFullPathListRecursion(ArrayList<String> fileList, String strPath) {
        File dir = new File(strPath);
        File[] files = dir.listFiles();

        if (files == null)
            return;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                getAllFilesFullPathList(fileList, files[i].getAbsolutePath());
            } else {
                String strFileName = files[i].getAbsolutePath();
                // EsLog.i("VideoFileUtil", "fileFullName:" + strFileName);
                fileList.add(strFileName);
            }
        }

    }
 public static void getAllFilesNameList(ArrayList<String> fileList, String path, boolean hasDot) {
        LinkedList<File> list = new LinkedList<File>();
        File dir = new File(path);
        File file[] = dir.listFiles();
        if (file == null)
            return;
        for (int i = 0; i < file.length; i++) {
            if (file[i].isDirectory())
                list.add(file[i]);
            else {

                String strFileName = file[i].getName();
                // EsLog.i("VideoFileUtil", "fileName:" + strFileName);
                if (!hasDot) {
                    strFileName = getFileNameNoEx(strFileName);
                }
                fileList.add(strFileName);
            }
        }
        File tmp;
        while (!list.isEmpty()) {
            tmp = list.removeFirst();// �׸�Ŀ¼
            if (tmp.isDirectory()) {
                file = tmp.listFiles();
                if (file == null)
                    continue;
                for (int i = 0; i < file.length; i++) {
                    if (file[i].isDirectory())
                        list.add(file[i]);// Ŀ¼�����Ŀ¼�б?�ؼ�
                    else {
                        String strFileName = file[i].getName();
                        // EsLog.i("VideoFileUtil", "fileName:" + strFileName);
                        if (!hasDot) {
                            strFileName = getFileNameNoEx(strFileName);
                        }
                        fileList.add(strFileName);
                    }
                }
            } else {
                String strFileName = tmp.getName();
                // EsLog.i("VideoFileUtil", "fileName:" + strFileName);
                if (!hasDot) {
                    strFileName = getFileNameNoEx(strFileName);
                }
                fileList.add(strFileName);
            }
        }
    }
  public static void getAllFilesNameListRecursion(ArrayList<String> fileList, String strPath, boolean hasDot) {
        File dir = new File(strPath);
        File[] files = dir.listFiles();

        if (files == null)
            return;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                getAllFilesNameList(fileList, files[i].getAbsolutePath(), hasDot);
            } else {
                String strFileName = files[i].getName();
                // EsLog.i("VideoFileUtil", "fileName:" + strFileName);
                if (!hasDot) {
                    strFileName = getFileNameNoEx(strFileName);
                }
                fileList.add(strFileName);
            }
        }
    }
 public static void getAllFilesList(List<String> filePathList, List<String> fileNameList, String path,
                                       boolean hasDot) {
        LinkedList<File> list = new LinkedList<File>();
        File dir = new File(path);
        File file[] = dir.listFiles();
        if (file == null)
            return;
        for (int i = 0; i < file.length; i++) {
            if (file[i].isDirectory())
                list.add(file[i]);
            else {

                String strFilePath = file[i].getAbsolutePath();
                String strFileName = file[i].getName();
                // EsLog.i("VideoFileUtil", "strFilePath:" + strFilePath);
                // EsLog.i("VideoFileUtil", "fileName:" + strFileName);
                if (!hasDot) {
                    strFileName = getFileNameNoEx(strFileName);
                }
                filePathList.add(strFilePath);
                fileNameList.add(strFileName);
            }
        }
        File tmp;
        while (!list.isEmpty()) {
            tmp = list.removeFirst();
            if (tmp.isDirectory()) {
                file = tmp.listFiles();
                if (file == null)
                    continue;
                for (int i = 0; i < file.length; i++) {
                    if (file[i].isDirectory())
                        list.add(file[i]);
                    else {
                        String strFilePath = file[i].getAbsolutePath();
                        String strFileName = file[i].getName();
                        // EsLog.i("VideoFileUtil", "strFilePath:" + strFilePath);
                        // EsLog.i("VideoFileUtil", "fileName:" + strFileName);
                        if (!hasDot) {
                            strFileName = getFileNameNoEx(strFileName);
                        }
                        filePathList.add(strFilePath);
                        fileNameList.add(strFileName);
                    }
                }
            } else {
                String strFilePath = tmp.getAbsolutePath();
                String strFileName = tmp.getName();
                // EsLog.i("VideoFileUtil", "strFilePath:" + strFilePath);
                // EsLog.i("VideoFileUtil", "fileName:" + strFileName);
                if (!hasDot) {
                    strFileName = getFileNameNoEx(strFileName);
                }
                filePathList.add(strFilePath);
                fileNameList.add(strFileName);
            }
        }
    }
 public static void getAllFilesListRecursion(ArrayList<String> filePathList, ArrayList<String> fileNameList,
                                                String strPath, boolean hasDot) {
        File dir = new File(strPath);
        File[] files = dir.listFiles();

        if (files == null)
            return;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                getAllFilesList(filePathList, fileNameList, files[i].getAbsolutePath(), hasDot);
            } else {
                String strFilePath = files[i].getAbsolutePath();
                String strFileName = files[i].getName();
                // EsLog.i("VideoFileUtil", "strFilePath:" + strFilePath);
                // EsLog.i("VideoFileUtil", "fileName:" + strFileName);
                if (!hasDot) {
                    strFileName = getFileNameNoEx(strFileName);
                }
                filePathList.add(strFilePath);
                fileNameList.add(strFileName);
            }
        }
    }

    /*
     * 获取后缀名
     *
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
 /*
     * 获取文件名称去后缀名
     * @param filePath 带文件路径的文件名 /storage/0/DCIM/IMG_20160411143029187.JPG
     * @return 返回去掉文件名的文件路径 IMG_20160411143029187
     */
    public static String getFilePathByName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            try {
                int dot = filename.lastIndexOf('.');
                int separ = filename.lastIndexOf(File.separator);
                if ((dot > -1) && (dot < (filename.length() - 1))) {
                    return filename.substring(separ + 1, dot);
                }
                if ((separ > -1) && (separ < (filename.length()))) {
                    return filename.substring(separ + 1, filename.length());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return filename;
    }

    /**
     * @param filePath 带文件路径的文件名 eg:/storage/0/DCIM/IMG_20160411143029187.JPG
     * @return 返回去掉文件名的文件路径 eg:/storage/0/DCIM
     */
    public static String getFilePathByPath(String filePath) {
        if ((filePath != null) && (filePath.length() > 0)) {
            int dot = filePath.lastIndexOf(File.separator);
            if ((dot > -1) && (dot < (filePath.length()))) {
                return filePath.substring(0, dot);
            }
            return null;
        }

        return null;
    }
  /**
     * @param filePath 带文件路径的文件名 eg:/storage/0/DCIM/IMG_20160411143029187.JPG
     * @return 返回去掉文件路径的文件名 eg:IMG_20160411143029187.JPG
     */
    public static String getFileNameByPath(String filePath) {
        if ((filePath != null) && (filePath.length() > 0)) {
            int dot = filePath.lastIndexOf(File.separator);
            if ((dot > -1) && (dot < (filePath.length()))) {
                return filePath.substring(dot + 1, filePath.length());
            }
            return null;
        }

        return null;
    }

    /**
     * @param filename 带/不带文件路径的文件名 eg:/storage/0/DCIM/IMG_20160411143029187.JPG  or  DCIM/IMG_20160411143029187.JPG
     * @return 返回去掉文件路径的文件名 eg:/storage/0/DCIM/IMG_20160411143029187  or  IMG_20160411143029187
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    public static boolean isAssetsFileExist(Context context, String assetDir, String fileName) {
        boolean ret = false;
        String[] files;
        try {
            files = context.getResources().getAssets().list(assetDir);
        } catch (IOException e) {
            e.printStackTrace();
            return ret;
        }

        for (int i = 0; i < files.length; i++) {
            if (fileName.equalsIgnoreCase(files[i])) {
                ret = true;
                break;
            }
        }
        return ret;
    }
 public static boolean copyFile(String srcFilePath, String desFilePath, Handler handler) {
        if (srcFilePath == null || desFilePath == null) {
            return false;
        }

        File inFile = new File(srcFilePath);
        if (!inFile.exists()) {
            return true;
        }

        InputStream inStream = null;
        FileOutputStream fs = null;

        try {
            long bytesum = 0;
            int byteread = 0;

            inStream = new FileInputStream(inFile); // 读入原文件
            fs = new FileOutputStream(desFilePath);
            byte[] buffer = new byte[1024 * 32];
            int progress = 0;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread; // 字节数 文件大小
                fs.write(buffer, 0, byteread);
                int progressTmp = (int) (bytesum * 100 / inFile.length());
                if (progress != progressTmp) {
                    progress = progressTmp;
                    if (handler != null) {
                        Message msg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putLong("progress", bytesum);
                        bundle.putLong("total", inFile.length());
                        msg.what = 0;
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                    inStream = null;

                } catch (Exception e2) {
                    // TODO: handle exception
                    e2.printStackTrace();
                }
            }
            if (fs != null) {
                try {
                    fs.flush();
                    fs.close();
                    fs = null;

                } catch (Exception e3) {
                    // TODO: handle exception
                    e3.printStackTrace();
                }
            }
        }
        return true;
    }
 public static boolean copyFile(String srcFilePath, String desFilePath) {
        if (srcFilePath == null || desFilePath == null) {
            return false;
        }

        File inFile = new File(srcFilePath);
        if (!inFile.exists()) {
            return false;
        }

        InputStream inStream = null;
        FileOutputStream fs = null;

        try {
            int bytesum = 0;
            int byteread = 0;

            inStream = new FileInputStream(inFile); // 读入原文件
            File desDirFile = new File(desFilePath).getParentFile();
            if (!desDirFile.exists()) {
                desDirFile.mkdirs();
            }
            fs = new FileOutputStream(desFilePath);
            byte[] buffer = new byte[1024 * 32];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread; // 字节数 文件大小
                fs.write(buffer, 0, byteread);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                    inStream = null;

                } catch (Exception e2) {
                    // TODO: handle exception
                    e2.printStackTrace();
                }
            }
            if (fs != null) {
                try {
                    fs.flush();
                    fs.close();
                    fs = null;

                } catch (Exception e3) {
                    // TODO: handle exception
                    e3.printStackTrace();
                }
            }
        }
        return true;
    }
 public static boolean copyRawFileToSdcard(Context context, int rawId, String path) {
        try {
            BufferedOutputStream bufEcrivain = new BufferedOutputStream((new FileOutputStream(path)));
            BufferedInputStream VideoReader = new BufferedInputStream(context.getResources().openRawResource(rawId));
            byte[] buff = new byte[32 * 1024];
            int len;
            while ((len = VideoReader.read(buff)) > 0) {
                bufEcrivain.write(buff, 0, len);
            }
            bufEcrivain.flush();
            bufEcrivain.close();
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    public static void copyAssetsToSdCard(Context context, String assetDir, String dir, String copyFileName) {
        String[] files;
        try {
            files = context.getResources().getAssets().list(assetDir);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        File mWorkingPath = new File(dir);
        // if this directory does not exists, make one.
        if (!mWorkingPath.exists()) {
            if (!mWorkingPath.mkdirs()) {

            }
        }

        for (int i = 0; i < files.length; i++) {
            try {
                String fileName = files[i];
                // we make sure file name not contains '.' to be a folder.
                if (!fileName.contains(".")) {
                    if (0 == assetDir.length()) {
                        copyAssetsToSdCard(context, fileName, dir + fileName + File.separator, copyFileName);
                    } else {
                        copyAssetsToSdCard(context, assetDir + "/" + fileName, dir + fileName + File.separator,
                                copyFileName);
                    }
                    continue;
                }

                if (copyFileName != null && !copyFileName.equalsIgnoreCase(fileName)) {
                    continue;
                }

                File outFile = new File(mWorkingPath, fileName);
                if (outFile.exists())
                    outFile.delete();
                InputStream in = null;
                if (0 != assetDir.length())
                    in = context.getAssets().open(assetDir + File.separator + fileName);
                else
                    in = context.getAssets().open(fileName);
                OutputStream out = new FileOutputStream(outFile);

                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                in.close();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888 : Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        // canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    // ����Դ�л�ȡBitmap
    public static Bitmap getBitmapByRid(Context context, int rid) {
        Resources res = context.getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, rid);
        return bmp;
    }

    // Bitmap �� byte[]

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    // byte[] �� Bitmap

    public static Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    // Bitmap to Drawable
    public static Drawable bitmap2drawable(Resources res, Bitmap b) {
        if (b == null || res == null) {
            return null;
        }
        return new BitmapDrawable(res, b);
    }
 // Bitmap to Drawable
    public static Drawable bitmap2drawable(Context context, Bitmap b) {
        if (b == null || context == null) {
            return null;
        }
        return new BitmapDrawable(context.getResources(), b);
    }

    // ��assets�ļ�����Դȡ��,����ͼƬ��bitmapת����drawable��ʽ
    public static Drawable getDrawableFromAssetFile(Context context, String fileName) {
        Bitmap image = null;
        BitmapDrawable drawable = null;
        try {
            AssetManager am = context.getAssets();
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            drawable = new BitmapDrawable(context.getResources(), image);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return drawable;
    }

    public static Bitmap getBitmapFromSDFile(String filePath, Options options) {

        Bitmap b = null;
        try {
            b = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError err) {
            err.printStackTrace();
        }
        return b;
    }

    public static Drawable zoomDrawable(Drawable drawable, int w, int h) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap oldbmp = drawableToBitmap(drawable);
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true);
        return new BitmapDrawable(null, newbmp);
    }

    public static boolean lnsFile(String srcPath, String destPath) {
        String cmds = "ln -s " + srcPath + " " + destPath;
        try {
            Process lnProc = Runtime.getRuntime().exec(cmds);
            BufferedReader mReader = new BufferedReader(new InputStreamReader(lnProc.getInputStream()), 1024);
            String line = null;

            if ((line = mReader.readLine()) != null) {
            }

            return true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }

    }
public static String getMetaDataValue(Context context, String name, String def) {
        String value = getMetaDataValue(context, name);
        return (value == null) ? def : value;
    }

    private static String getMetaDataValue(Context context, String name) {
        Object value = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            ApplicationInfo applicationInfo;
            applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);//128
            if (applicationInfo != null && applicationInfo.metaData != null) {
                value = applicationInfo.metaData.get(name);
            }
        } catch (Exception e) {
            // throw new RuntimeException(
            // "Could not read the name in the manifest file.", e);
            e.printStackTrace();
            return null;
        }
        // if (value == null) {
        // throw new RuntimeException("The name '" + name
        // + "' is not defined in the manifest file's meta data.");
        // }
        return value.toString();
    }


    public static boolean saveBitmapToSdCardJPG(Bitmap bitmap, String filePath, final int quality) {
        if (filePath == null || bitmap == null) {
            return false;
        }

        boolean saveRet = false;
        try {
            FileOutputStream fout = new FileOutputStream(filePath);
            saveRet = bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fout);
            if (fout != null) {
                fout.close();
                fout = null;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return saveRet;
    }

    public static boolean saveBitmapToSdCardPNG(Bitmap bitmap, String filePath, final int quality) {
        if (filePath == null || bitmap == null) {
            return false;
        }

        boolean saveRet = false;
        try {
            FileOutputStream fout = new FileOutputStream(filePath);
            saveRet = bitmap.compress(Bitmap.CompressFormat.PNG, quality, fout);
            if (fout != null) {
                fout.close();
                fout = null;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return saveRet;
    }

    public static Bitmap combineBitmapAsSameSize(Bitmap background, Bitmap foreground, boolean useBackGround) {
        if (background == null || foreground == null) {
            return null;
        }

        Bitmap newbmp;
        if (useBackGround) {
            newbmp = background;
        } else {
            Config config = background.getConfig();
            if (config == null) {
                config = Config.ARGB_8888;
            }
            newbmp = background.copy(config, true);
        }

        Canvas cv = new Canvas(newbmp);
        cv.drawBitmap(background, 0, 0, null);// 在 0,0坐标开始画入bg
        cv.drawBitmap(foreground, 0, 0, null);// 在 0,0坐标开始画入fg ,可以从任意位置画入
        cv.save();// 保存
        cv.restore();// 存储
        return newbmp;
    }
public static Bitmap combineBitmapAtCenter(Bitmap background, Bitmap foreground, boolean useBackGround) {
        if (background == null || foreground == null) {
            return null;
        }
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        Bitmap newbmp;
        if (useBackGround) {
            newbmp = background;
        } else {
            Config config = background.getConfig();
            if (config == null) {
                config = Config.ARGB_8888;
            }
            newbmp = background.copy(config, true);
        }

        Canvas cv = new Canvas(newbmp);
        cv.drawBitmap(background, 0, 0, null);
        cv.drawBitmap(foreground, (bgWidth - fgWidth) / 2, (bgHeight - fgHeight) / 2, null);
        cv.save();
        cv.restore();
        return newbmp;
    }
/**************************
     * begin 加UUID新增代码
     ********************************************/


    public static boolean getSdcardIsReady() {
        String sdready = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(sdready) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(sdready)) {
            return true;
        }

        return false;
    }


    /****************************
     * end 加UUID新增代码
     ******************************************/

    public static void RecycleBitmap(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        System.gc();
    }

    /**
     * 保存Res资源文件到SD卡
     *
     * @param content
     * @param path
     * @param rawId
     * @throws IOException
     */
    public static void saveVideoToSdcard(Context content, String path, int rawId) throws IOException {
        BufferedOutputStream bufEcrivain = new BufferedOutputStream((new FileOutputStream(path)));
        BufferedInputStream VideoReader = new BufferedInputStream(content.getResources().openRawResource(rawId));
        byte[] buff = new byte[32 * 1024];
        int len;
        while ((len = VideoReader.read(buff)) > 0) {
            bufEcrivain.write(buff, 0, len);
        }
        bufEcrivain.flush();
        bufEcrivain.close();
    }

    /**
     * 复制文件或文件夹
     *
     * @param srcPath
     * @param destDir 目标文件所在的目录
     * @return
     */
    public static boolean copyGeneralFile(String srcPath, String destDir) {
        boolean flag = false;
        File file = new File(srcPath);
        if (!file.exists()) {
            // System.out.println("源文件或源文件夹不存在!");
            return false;
        }
        if (file.isFile()) { // 源文件
            // System.out.println("下面进行文件复制!");
            flag = copyFileToDir(srcPath, destDir);
        } else if (file.isDirectory()) {
            // System.out.println("下面进行文件夹复制!");
            flag = copyDirectory(srcPath, destDir, true);
        }

        return flag;
    }

    /**
     * 复制文件
     *
     * @param srcPath 源文件绝对路径
     * @param destDir 目标文件所在目录
     * @return boolean
     */
    public static boolean copyFileToDir(String srcPath, String destDir) {
        boolean flag = false;

        File srcFile = new File(srcPath);
        if (!srcFile.exists()) { // 源文件不存在
            // System.out.println("源文件不存在");
            return false;
        }
        // 获取待复制文件的文件名
        String fileName = srcPath.substring(srcPath.lastIndexOf(File.separator));
        String destPath = destDir + fileName;
        if (destPath.equals(srcPath)) { // 源文件路径和目标文件路径重复
            // System.out.println("源文件路径和目标文件路径重复!");
            return false;
        }
        File destFile = new File(destPath);
        if (destFile.exists() && destFile.isFile()) { // 该路径下已经有一个同名文件
            // System.out.println("目标目录下已有同名文件!");
            return false;
        }

        File destFileDir = new File(destDir);
        destFileDir.mkdirs();
        try {
            FileInputStream fis = new FileInputStream(srcPath);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int c;
            while ((c = fis.read(buf)) != -1) {
                fos.write(buf, 0, c);
            }
            fis.close();
            fos.close();

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        // if (flag) {
        // System.out.println("复制文件成功!");
        // }

        return flag;
    }

    /**
     * @param srcPath          源文件夹路径
     * @param destDir          目标文件夹所在目录
     * @param isCopySrcDirName 是否需要在目标文件夹目录下创建一个与源文件夹相同的目录
     * @return
     */
    public static boolean copyDirectory(String srcPath, String destDir, boolean isCopySrcDirName) {
        // System.out.println("复制文件夹开始!");
        boolean flag = false;

        File srcFile = new File(srcPath);
        if (!srcFile.exists()) { // 源文件夹不存在
            // System.out.println("源文件夹不存在");
            return false;
        }
        // 获得待复制的文件夹的名字,比如待复制的文件夹为"E://dir"则获取的名字为"dir"
        String dirName = getDirName(srcPath);
        // 目标文件夹的完整路径
        String destPath = destDir;
        if (isCopySrcDirName) {
            destPath += File.separator + dirName;
        }
        // System.out.println("目标文件夹的完整路径为:" + destPath);

        if (destPath.equals(srcPath)) {
            // System.out.println("目标文件夹与源文件夹重复");
            return false;
        }
        File destDirFile = new File(destPath);
        // if (destDirFile.exists()) { // 目标位置有一个同名文件夹
        // System.out.println("目标位置已有同名文件夹!");
        // return false;
        // }
        if (!destDirFile.exists()) {
            destDirFile.mkdirs(); // 生成目录
        }

        File[] fileList = srcFile.listFiles(); // 获取源文件夹下的子文件和子文件夹
        if (fileList.length == 0) { // 如果源文件夹为空目录则直接设置flag为true,这一步非常隐蔽,debug了很久
            flag = true;
        } else {
            for (File temp : fileList) {
                if (temp.isFile()) { // 文件
                    flag = copyFileToDir(temp.getAbsolutePath(), destPath);
                } else if (temp.isDirectory()) { // 文件夹
                    flag = copyDirectory(temp.getAbsolutePath(), destPath, isCopySrcDirName);
                }
                if (!flag) {
                    break;
                }
            }
        }

        // if (flag) {
        // System.out.println("复制文件夹成功!");
        // }

        return flag;
    }

    /**
     * 获取待复制文件夹的文件夹名
     * 文件夹为"E://dir"则获取的名字为"dir"
     *
     * @param dir
     * @return String
     */
    public static String getDirName(String dir) {
        if (dir.endsWith(File.separator)) { // 如果文件夹路径以"//"结尾,则先去除末尾的"//"
            dir = dir.substring(0, dir.lastIndexOf(File.separator));
        }
        return dir.substring(dir.lastIndexOf(File.separator) + 1);
    }

    /**
     * 通过文件路径获取文件夹的全路径
     * 文件夹为"E://dir/1.txt"则获取的名字为"E://dir"
     *
     * @param dir
     * @return String
     */
    public static String getDirNameByFilePath(String dir) {
        if (dir.endsWith(File.separator)) { // 如果文件夹路径以"//"结尾,则先去除末尾的"//"
            dir = dir.substring(0, dir.lastIndexOf(File.separator));
            return dir;
        }
        return dir.substring(0, dir.lastIndexOf(File.separator));
    }
/**
     * 删除文件或文件夹
     *
     * @param path 待删除的文件的绝对路径
     * @return boolean
     */
    public static boolean deleteGeneralFile(String path) {
        if (path == null)
            return false;
        boolean flag = false;

        File file = new File(path);
        if (!file.exists()) { // 文件不存在
            // System.out.println("要删除的文件不存在!");
            return false;
        }

        if (file.isDirectory()) { // 如果是目录,则单独处理
            flag = deleteDirectory(file.getAbsolutePath());
        } else if (file.isFile()) {
            flag = deleteFile(file);
        }

        // if (flag) {
        // System.out.println("删除文件或文件夹成功!");
        // }

        return flag;
    }

    /**
     * 删除文件
     *
     * @param file
     * @return boolean
     */
    public static boolean deleteFile(File file) {
        return file.delete();
    }

    /**
     * 删除目录及其下面的所有子文件和子文件夹,注意一个目录下如果还有其他文件或文件夹
     * 则直接调用delete方法是不行的,必须待其子文件和子文件夹完全删除了才能够调用delete
     *
     * @param path path为该目录的路径
     */
    public static boolean deleteDirectory(String path) {
        boolean flag = true;
        File dirFile = new File(path);
        if (!dirFile.isDirectory()) {
            return flag;
        }
        File[] files = dirFile.listFiles();
        for (File file : files) { // 删除该文件夹下的文件和文件夹
            // Delete file.
            if (file.isFile()) {
                flag = deleteFile(file);
            } else if (file.isDirectory()) {// Delete folder
                flag = deleteDirectory(file.getAbsolutePath());
            }
            if (!flag) { // 只要有一个失败就立刻不再继续
                break;
            }
        }
        flag = dirFile.delete(); // 删除空目录
        return flag;
    }

    /**
     * 由上面方法延伸出剪切方法:复制+删除
     *
     * @param destDir 同上
     */
    public static boolean cutGeneralFile(String srcPath, String destDir) {
        if (!copyGeneralFile(srcPath, destDir)) {
            // System.out.println("复制失败导致剪切失败!");
            return false;
        }
        if (!deleteGeneralFile(srcPath)) {
            // System.out.println("删除源文件(文件夹)失败导致剪切失败!");
            return false;
        }

        // System.out.println("剪切成功!");
        return true;
    }
 /**
     * Db最新版本写入文件内容
     *
     * @param filePath
     * @param newVersion
     * @return
     */
    public static boolean setFileDbOldVersion(String filePath, int newVersion) {
        try {
            FileOutputStream out = new FileOutputStream(new File(filePath));
            out.write((newVersion + "").getBytes());
            out.close();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 获取Db旧版本文件内容
     *
     * @param filePath
     * @return
     */
    public static int getFileDbNewVersion(String filePath) {
        try {
            RandomAccessFile f = new RandomAccessFile(filePath, "r");
            byte[] bytes = new byte[(int) f.length()];
            f.readFully(bytes);
            f.close();
            return Integer.valueOf(new String(bytes));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0;
    }

    /**
     * 文件大小格式化字串
     *
     * @param size
     * 文件大小,单位字节
     * @param type
     * 需要格式化的类型
     * @return formatSize 格式化的字串
     */
    public static final long FILE_SIZE_FORMAT_TYPE_KB = 1024;

    public static final long FILE_SIZE_FORMAT_TYPE_MB = FILE_SIZE_FORMAT_TYPE_KB * 1024;

    public static final long FILE_SIZE_FORMAT_TYPE_GB = FILE_SIZE_FORMAT_TYPE_MB * 1024;

    public static final long FILE_SIZE_FORMAT_TYPE_TB = FILE_SIZE_FORMAT_TYPE_GB * 1024;

    /**
     * 获取文件数值MB
     *
     * @param size
     * @return
     */
    public static double getFileSizeMB(long size) {
        return MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_MB, 2, BigDecimal.ROUND_HALF_UP);
    }

    public static String getFileSizeFormat(long size, long type) {
        return getFileSizeFormat(size, 2, type);
    }
/**
     * 文件大小格式化
     *
     * @param size
     * @param type
     * @return
     */
    public static String getFileSizeFormat(long size, int scale, long type) {

        String formatSize;
        if (type == FILE_SIZE_FORMAT_TYPE_KB) {
            formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_KB, scale, BigDecimal.ROUND_HALF_UP) + "KB";
        } else if (type == FILE_SIZE_FORMAT_TYPE_MB) {
            if (size >= FILE_SIZE_FORMAT_TYPE_MB) {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_MB, scale, BigDecimal.ROUND_HALF_UP)
                        + "MB";
            } else {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_KB, scale, BigDecimal.ROUND_HALF_UP)
                        + "KB";
            }
        } else if (type == FILE_SIZE_FORMAT_TYPE_GB) {
            if (size >= FILE_SIZE_FORMAT_TYPE_GB) {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_GB, scale, BigDecimal.ROUND_HALF_UP)
                        + "GB";
            } else if (size >= FILE_SIZE_FORMAT_TYPE_MB) {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_MB, scale, BigDecimal.ROUND_HALF_UP)
                        + "MB";
            } else {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_KB, scale, BigDecimal.ROUND_HALF_UP)
                        + "KB";
            }
        } else if (type == FILE_SIZE_FORMAT_TYPE_TB) {
            if (size >= FILE_SIZE_FORMAT_TYPE_TB) {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_TB, scale, BigDecimal.ROUND_HALF_UP)
                        + "TB";
            } else if (size >= FILE_SIZE_FORMAT_TYPE_GB) {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_GB, scale, BigDecimal.ROUND_HALF_UP)
                        + "GB";
            } else if (size >= FILE_SIZE_FORMAT_TYPE_MB) {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_MB, scale, BigDecimal.ROUND_HALF_UP)
                        + "MB";
            } else {
                formatSize = MathUtil.round(size * 1.0 / FILE_SIZE_FORMAT_TYPE_KB, scale, BigDecimal.ROUND_HALF_UP)
                        + "KB";
            }
        } else {
            formatSize = size + "B";
        }

        return formatSize;
    }

    private static String[] proj = {MediaStore.Images.Media.DATA, MediaStore.Video.Media.DATA};

    // 获得U盘目录
    static Map<String, File> externalLocations = null;

    public static String getUdiskPath() {
        // return File.separator + "udisk";
        if (externalLocations == null) {
            externalLocations = ExternalStorage.getAllStorageLocations();
        }
        // File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
        File externalSdCard = externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);
        if (externalSdCard == null) {
            String udiskRootPath = getExtStoragesPath();
            if (udiskRootPath == null) {
                return getSdcardPath();
            } else {
                return udiskRootPath;
            }
        }
        return externalSdCard.getAbsolutePath();
    }

    // 获得SD卡目录
    public static String getSdcardPath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }
/**
     * 根据Uri获取(文件)图片绝对路径,解决Android4.4以上版本Uri转换
     *
     * @param context
     * @param imageUri
     */
    @TargetApi(19)
    public static String getUriAbsolutePath(Context context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
                if (isExternalStorageDocument(imageUri)) {
                    String docId = DocumentsContract.getDocumentId(imageUri);
                    String[] split = docId.split(":");
                    String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        //内置卡路径  /storage/emulated/0
                        return getSdcardPath() + "/" + split[1];
                    } else {//
                        //取外置卡路径 /mnt/media_rw/sdcard1
                        String path = getUdiskPath() + "/" + split[1];
                        if (!isExistFile(path)) {
                            //特殊处理外置卡位置路径  /storage/sdcard1
                            path = "/storage/sdcard1/" + split[1];
                            if (!isExistFile(path)) {
                                path = getSdcardPath() + "/" + split[1];
                                if (!isExistFile(path)) {
                                    return null;
                                }
                            }
                        }
                        return path;
                    }
                } else if (isDownloadsDocument(imageUri)) {
                    String id = DocumentsContract.getDocumentId(imageUri);
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                    return getDataColumn(context, contentUri, null, null);
                } else if (isMediaDocument(imageUri)) {
                    String docId = DocumentsContract.getDocumentId(imageUri);
                    String[] split = docId.split(":");
                    String type = split[0];
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    String selection = MediaStore.Images.Media._ID + "=?";
                    String[] selectionArgs = new String[]{split[1]};
                    return getDataColumn(context, contentUri, selection, selectionArgs);
                } else {
                    //com.goseet.VidTrim.documents包名第三方返回路径处理
                    String docId = DocumentsContract.getDocumentId(imageUri);
                    return docId;
                }
            } // MediaStore (and general)
            else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
                // Return the remote address
                if (isGooglePhotosUri(imageUri))
                    return imageUri.getLastPathSegment();
                return getDataColumn(context, imageUri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
                return imageUri.getPath();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
 /**
     * Uri获取资源文件详情路径
     *
     * @param uri
     * @return
     */
    @SuppressLint("NewApi")
    public static String getLocalPathByUri(Context context, Uri uri) {
        String[] fileSplit = {};
        Uri paramUri = uri;
        String filePath = null;
        // ACTION_GET_CONTENT得到的URI
        // content://com.android.providers.media.documents/document/video%3A648
        // ACTION_PICK得到的URI content://media/external/video/media/648
        if (uri == null) {
            return null;
        }
        if (Build.VERSION.SDK_INT >= 19) {
            // 备用方案
            // String path= GetPathFromUri4kitkat.getPath(context, uri);
            // if(path!=null){
            // return path;
            // }
            if (DocumentsContract.isDocumentUri(context, uri)) {
                String wholeID = DocumentsContract.getDocumentId(uri);
                if (wholeID == null)
                    wholeID = "";
                String[] wholeIdArr = wholeID.split(":");
                String id = wholeID;
                if (wholeIdArr.length > 1) {
                    // 友盟报下标错误,index=1,length=1
                    id = wholeIdArr[1];
                }
                String[] column = {MediaStore.Video.Media.DATA};
                String sel = MediaStore.Video.Media._ID + "=?";
                Cursor cursor;
                if (uri.toString().contains("video")) {
                    cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, column,
                            sel, new String[]{id}, null);
                } else {
                    cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column,
                            sel, new String[]{id}, null);
                }
                int columnIndex = cursor.getColumnIndex(column[0]);
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(columnIndex);
                }
                if (!cursor.isClosed()) {
                    cursor.close();
                }
                // 取值失败后
                if (filePath == null) {
                    filePath = getUriAbsolutePath(context, uri);
                }
                return filePath;
            }
        }
        // file:///storage/sdcard0/DCIM/1Videoshow/vshow_20140711172434.mp4
        // /external/video/media/101607
        // content://media/external/video/media/101607
        if (uri.toString().contains("file://")) {
            fileSplit = uri.toString().split("file://");
            filePath = fileSplit[1];
            if (!FilePlayerUtil.isExistFile(filePath)) {
                // filePath = filePath.replaceAll("%20", " ");//
                // 红米手机出现空格文件夹被转码为%20
                try {
                    filePath = URLDecoder.decode(filePath, "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return filePath;
        } else if (uri.toString().contains("flg=")) { // 小米平板
            fileSplit = uri.toString().split("flg=");
            paramUri = Uri.parse(fileSplit[0]);
        }
        if (paramUri == null)
            return null;
        try {
            // managedQuery已经弃用,使用getContentResolver().query代替,自己管理cursor
            // Cursor actualimagecursor = managedQuery(uri, proj, null,
            // null,
            // null);
            Cursor cursor = context.getContentResolver().query(paramUri, proj,
                    // 字段 没有字段 就是查询所有信息 相当于SQL语句中的 “ * ”
                    null, // 查询条件
                    null, // 条件的对应?的参数
                    null);
            if (cursor != null) {
                int index = 0;
                for (int i = 0; i < proj.length; i++) {
                    index = cursor.getColumnIndexOrThrow(proj[i]);
                }
                cursor.moveToFirst();
                filePath = cursor.getString(index);
                // if (Integer.parseInt(Build.VERSION.SDK) < 14)
                if (!cursor.isClosed()) {
                    cursor.close();
                }
            }
        } catch (Exception ex) {
            // Permission Denial
            ex.printStackTrace();
        }
        return filePath;
    }
 /**
     * 通过Uri获取文件在本地存储的真实路径
     *
     * @param context
     * @param contentUri
     * @return
     */
    public static String getRealPathFromURI(Context context, Uri contentUri) {
        try {
            if (contentUri == null)
                return null;
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(contentUri, proj, // Which
                    // columns
                    // to
                    // return
                    null, // WHERE clause; which rows to return (all rows)
                    null, // WHERE clause selection arguments (none)
                    null); // Order-by clause (ascending by name)
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(column_index);
            if (!cursor.isClosed())
                cursor.close();
            return path;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isExternalGoseetVidTrimDocuments(Uri uri) {
        return "com.goseet.VidTrim.documents".equals(uri.getAuthority()) ||
                "com.goseet.VidTrimPro.localstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
 /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * 将字节码写入到文本文件中
     */
    public static void writeTextFile(String filePath, byte[] bytes, boolean append) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file, append);// openFileOutput(filePath,MODE_PRIVATE);
            fos.write(bytes);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 将字符串写入到文本文件中
     */
    public static void writeTextFile(String filePath, String content, boolean append) {
        //每次写入时,都换行写
        String strContent = content + "\n";
        try {
            File file = new File(filePath);
            if (!append) {
                file.createNewFile();
            } else {
                if (!file.exists()) {
                    file.createNewFile();
                }
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 限制字符串中不存在特殊字符
     */

    public static boolean onLimitSpecialString(String str) {
        if (str.contains("\'") || str.contains("\"") || str.contains("/") ||
                str.contains("\\") || str.contains(":") || str.contains("*") ||
                str.contains("?") || str.contains("<") || str.contains(">") ||
                str.contains("|")) {
            return true;
        } else {
            return false;
        }
    }
private static final long MAX_VIDEO_SIZE = 2; // 不支持视频最大的size:2G


    public static String getStackFileName() {
        return Thread.currentThread().getStackTrace()[2].getFileName();
    }

    public static String getStackMethodName() {
        return Thread.currentThread().getStackTrace()[2].getMethodName();
    }

    public static int getStackLineNum() {
        return Thread.currentThread().getStackTrace()[2].getLineNumber();
    }

    /**
     * 通过content 类型URI返回图片的真实路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getImagePathFromUri(Activity context, Uri uri) {
//        String myImageUrl = "content://media/external/images/media/8312";
//        Uri uri = Uri.parse(myImageUrl);

        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();


        String img_path = cursor.getString(actual_image_column_index);
//        File file = new File(img_path);
//        Uri fileUri = Uri.fromFile(file);
        if (!cursor.isClosed()) {
            cursor.close();
        }
        return img_path;
    }

    /**
     * 通过content 类型URI返回视频的真实路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getVideoPathFromUri(Activity context, Uri uri) {
//        String myImageUrl = "content://media/external/images/media/8312";
//        Uri uri = Uri.parse(myImageUrl);

        String[] proj = {MediaStore.Video.Media.DATA};
        Cursor cursor = context.managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        cursor.moveToFirst();


        String img_path = cursor.getString(actual_image_column_index);
//        File file = new File(img_path);
//        Uri fileUri = Uri.fromFile(file);
        if (!cursor.isClosed()) {
            cursor.close();
        }
        return img_path;
    }

 /**
     * 通过外部路径返回 URI,形如(content://media/external/images/media/3483)
     *
     * @param context
     * @param picPath
     * @return
     */
    public static Uri getUriFromLoacalImageFilePath(Activity context, String picPath) {
        Uri mUri = Uri.parse("content://media/external/images/media");
        Uri mImageUri = null;

        Cursor cursor = context.managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null,
                null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            String data = cursor.getString(cursor
                    .getColumnIndex(MediaStore.MediaColumns.DATA));
            if (picPath.equals(data)) {
                int ringtoneID = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.MediaColumns._ID));
                mImageUri = Uri.withAppendedPath(mUri, ""
                        + ringtoneID);
                break;
            }
            cursor.moveToNext();
        }
        if (!cursor.isClosed()) {
            cursor.close();
        }
        return mImageUri;
    }


    /**
     * 通过外部路径返回 URI,形如(content://media/external/video/media/3483)
     *
     * @param context
     * @param videoPath
     * @return
     */
    public static Uri getUriFromLoacalVideoFilePath(Activity context, String videoPath) {

        Uri mUri = Uri.parse("content://media/external/video/media");
        Uri mImageUri = null;

        Cursor cursor = context.managedQuery(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null,
                null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            String data = cursor.getString(cursor
                    .getColumnIndex(MediaStore.MediaColumns.DATA));
            if (videoPath.equals(data)) {
                int ringtoneID = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.MediaColumns._ID));
                mImageUri = Uri.withAppendedPath(mUri, ""
                        + ringtoneID);
                break;
            }
            cursor.moveToNext();
        }
        if (!cursor.isClosed()) {
            cursor.close();
        }
        return mImageUri;
    }

    /**
     * 将流读入文件中
     *
     * @param ins
     * @param file
     */
    public static void inputstreamtofile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 private static final char[] HEX_CHAR = {

            '0', '1', '2', '3', '4', '5', '6', '7',

            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'

    };

    public static String toHexString(byte[] rawByteArray) {

        char[] chars = new char[rawByteArray.length * 2];

        for (int i = 0; i < rawByteArray.length; ++i) {

            byte b = rawByteArray[i];

            chars[i * 2] = HEX_CHAR[(b >>> 4 & 0x0F)];

            chars[i * 2 + 1] = HEX_CHAR[(b & 0x0F)];

        }

        return new String(chars);

    }
  /**
     * 通过反射获取通过FileProvider分享的文件路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getFileProviderUriToPath(Context context, Uri uri) {
        try {
            List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
            if (packs != null) {
                String fileProviderClassName = FileProvider.class.getName();
                for (PackageInfo pack : packs) {
                    ProviderInfo[] providers = pack.providers;
                    if (providers != null) {
                        for (ProviderInfo provider : providers) {
                            if (uri.getAuthority().equals(provider.authority)) {
                                if (provider.name.equalsIgnoreCase(fileProviderClassName)) {
                                    Class<FileProvider> fileProviderClass = FileProvider.class;
                                    try {
                                        Method getPathStrategy = fileProviderClass.getDeclaredMethod("getPathStrategy", Context.class, String.class);
                                        getPathStrategy.setAccessible(true);
                                        Object invoke = getPathStrategy.invoke(null, context, uri.getAuthority());
                                        if (invoke != null) {
                                            String PathStrategyStringClass = FileProvider.class.getName() + "$PathStrategy";
                                            Class<?> PathStrategy = Class.forName(PathStrategyStringClass);
                                            Method getFileForUri = PathStrategy.getDeclaredMethod("getFileForUri", Uri.class);
                                            getFileForUri.setAccessible(true);
                                            Object invoke1 = getFileForUri.invoke(invoke, uri);
                                            if (invoke1 instanceof File) {
                                                String filePath = ((File) invoke1).getAbsolutePath();
                                                return filePath;
                                            }
                                        }
                                    } catch (NoSuchMethodException e) {
                                        e.printStackTrace();
                                    } catch (InvocationTargetException e) {
                                        e.printStackTrace();
                                    } catch (IllegalAccessException e) {
                                        e.printStackTrace();
                                    } catch (ClassNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    break;
                                }
                                break;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
public static String getExtStoragesPath() {
        ArrayList<String> paths = new ArrayList<String>();
        Scanner scanner = null;
        try {
            scanner = new Scanner(new File("/proc/mounts"));
            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                // EdLog.i("Singlee", "line--->"+line);
                if (line.contains("secure")) {
                    continue;
                }
                if (line.contains("asec")) {
                    continue;
                }
                if (line.startsWith("/dev/block/vold/")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        paths.add(columns[1]);
                    }
                } else if (line.startsWith("/dev/fuse")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        paths.add(columns[1]);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        String defaultSdPath = Environment.getExternalStorageDirectory().getPath();



        if (paths.size() > 1) {
            String extPathString = paths.get(1);
            if (defaultSdPath.equals(extPathString)) {
                return null;
            }
            return extPathString;
        } else {
            if (paths.size() <= 0) {
                return null;
            }

            if (!paths.get(0).equals(defaultSdPath))// extsdcard exist!
            {
                return paths.get(0);
            } else {
                return null;
            }
        }

    }
}

相关文章

网友评论

      本文标题:FileUtils

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