Android开发:操作文件工具类封装


import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.crlgc.nofire.base.App;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.Collator;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.Locale;


public class FileUtils {

    public static String getAppBasePath() {
        String path = App.gFilePath;
        return path;
    }
    public static String getAssetJson(Context context,String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
    /**
     * 保存方法
     */
    public static void saveBitmap(Bitmap bmp, String fileName) {
        try {
            if (TextUtils.isEmpty(fileName)) {
                return;
            }
            // make sure this file exist
            makesureFileExist(fileName);
            FileOutputStream out = new FileOutputStream(fileName);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    // 获取指定utf-8编码文件内容,返回字节数组
    public static byte[] getFileDataByte(String path) {
        byte[] res = null;
        try {
            FileInputStream fin = new FileInputStream(path);
            int length = fin.available();
            if (length > 0) {
                byte[] buffer = new byte[length];
                fin.read(buffer);
                res = buffer;
            }
            fin.close();
        } catch (Exception e) {
            LogUtils.PST(e);
        }
        return res;
    }

    // 复制打包进入的文件
    public static void copyAssetsFile(Context context, String srcName,
                                      String destName) {
        String fname = getAppBasePath() + destName;
        File file = new File(fname);

        // 如果目标文件已存在,则不复制
        if (file.exists()) {
            return;
        }

        try {
            makesureFileExist(fname);

            InputStream inReadFile = context.getAssets().open(srcName);
            int size = inReadFile.available();
            if (size > 0) {
                byte[] buffer = new byte[size];
                inReadFile.read(buffer);
                FileOutputStream fos = new FileOutputStream(file, false);
                fos.write(buffer);
                fos.close();
            }
            inReadFile.close();
        } catch (Exception e) {
            LogUtils.PST(e);
        }
    }

    // 转换url地址为文件名,去掉http头和ip字段
    public static String convertFilenameFromUrl(String open_url, String param) {
        return convertFilenameFromUrl(open_url + "_" + param);
    }

    // 转换url地址为文件名,去掉http头和ip字段
    public static String convertFilenameFromUrl(String open_url) {
        String name = open_url;
        name = name.replace("http://", "");
        name = name.replace("https://", "");
        int pos = name.indexOf("/");
        if (pos > 0) {
            name = name.substring(pos);
        }
        name = name.replace("/", "_");
        name = name.replace("?", "_");
        name = name.replace("&", "_");
        name = name.replace("=", "_");
        return name;
    }

    // 数组保存为文件
    public static void saveAsFile(byte[] data, String fileName) {
        saveAsFile(data, fileName, false);
    }

    // 数组保存为文件
    public static void saveAsFile(byte[] data, String fileName, boolean append) {
        try {
            InputStream is = new ByteArrayInputStream(data);
            FileUtils.saveAsFile(is, fileName, false);
            is.close();
        } catch (IOException e) {
            LogUtils.PST(e);
        }
    }

    // 输入流保存为文件
    public static void saveAsFile(InputStream inputStream, String fileName) {
        saveAsFile(inputStream, fileName, false);
    }

    // 输入流保存为文件
    public static void saveAsFile(InputStream inputStream, String fileName,
                                  boolean append) {
        try {
            if (TextUtils.isEmpty(fileName)) {
                return;
            }
            // make sure this file exist
            makesureFileExist(fileName);

            OutputStream os = new FileOutputStream(fileName, append);
            byte[] buf = new byte[255];
            int len = 0;
            while ((len = inputStream.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            inputStream.close();
            os.flush();
            os.close();
        } catch (IOException e) {
            LogUtils.PST(e);
        }
    }

    // 确定指定文件是否存在,如果不存在,则创建空文件
    public static void makesureFileExist(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return;
        }
        // file path
        int index = fileName.lastIndexOf("/");
        File file = null;
        if (index != -1) {
            String filePath = fileName.substring(0, index);
            file = new File(filePath);
            if (!file.exists()) {
                boolean ret = file.mkdirs();
                LogUtils.d("mkdirs " + ret + " " + filePath);
            }
        }
        file = new File(fileName);
        if (!file.exists()) {// 确保文件存在
            try {
                file.createNewFile();
            } catch (Exception e) {
                LogUtils.PST(e);
            }
        }
    }

    /**
     * 删除文件
     *
     * @param fileName
     */

    public static void deleteFile(String fileName) {
        File file = new File(getAppBasePath() + fileName);
        if (file.exists()) {
            file.delete();
        }
    }

    public static int getFloderCount(File file) {
        int count = 0;
        File[] flist = file.listFiles();

        if (flist == null) {
            return 0;
        }

        int len = flist.length;

        for (int i = 0; i < len; i++) {
            if (!flist[i].isFile())
                count++;
        }
        return count;
    }

    private static boolean isNullDir(File file) {
        if (file != null) {
            File files[] = file.listFiles();
            if (files != null && files.length > 0) {
                return false;
            }
        }
        return true;
    }


    @SuppressWarnings("AlibabaUndefineMagicConstant")
    public static String getMIMEType(File f) {
        String type = "";
        String fileName = f.getName();
        String end = fileName.substring(fileName.lastIndexOf(".") + 1,
                fileName.length()).toLowerCase();

        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4") || end.equals("avi")) {
            type = "video/*";
        } else if (end.equals("htm") || end.equals("html")) {
            type = "text/html";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp") || end.equals("ico")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else {
            type = "text/plain";
        }
        return type;
    }

    // 递归删除文件及文件夹
    public static void deleteFileOrPath(String path) {
        File file = new File(path);
        deleteFileInfo(path);
        deleteFileOrPath(file);
    }

    /**
     * 删除文件后缀是info的文件
     *
     * @param path
     */
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    private static void deleteFileInfo(String path) {
        // TODO Auto-generated method stub
        if (path.endsWith(".tmp")) {
            path = path.substring(0, path.length() - 4);
        }
        File file = new File(path + ".info");
        if (file.exists()) {
            file.delete();
        }
    }

    // 递归删除文件及文件夹
    public static void deleteFileOrPath(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }

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

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

    private static class Sort implements Comparator<File> {
        @Override
        public int compare(File arg0, File arg1) {
            // TODO Auto-generated method stub
            String file1 = arg0.getName();
            String file2 = arg1.getName();
            Collator cmp = Collator.getInstance(Locale.CHINA);
            return cmp.compare(file1, file2);
        }
    }

    public static final int SIZETYPE_B = 1;// 获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;// 获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;// 获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;// 获取文件大小单位为GB的double值

    public static double getFileOrFilesSize(String filePath, int sizeType, String filterName) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file, filterName);
            } else {
                blockSize = getFileSize(file, filterName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FormetFileSize(blockSize, sizeType);
    }

    /**
     * 获取指定文件大小
     *
     * @param
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file, String filterName) throws Exception {
        long size = 0;
        if (file.exists()) {
            if (!TextUtils.isEmpty(filterName) && !file.getName().endsWith(filterName)) {
                return 0;
            }
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
        }
        return size;
    }

    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    private static long getFileSizes(File f, String filterName) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i], filterName);
            } else {
                size = size + getFileSize(flist[i], filterName);
            }
        }
        return size;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    private static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    private static double FormetFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.valueOf(df
                        .format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }

    /**
     * @param src 源文件路径
     * @param out 新文件路径
     */
    public static void coypFile(@NonNull String src, @NonNull String out) {
        File file = new File(src);
        if (!file.exists() || file.isDirectory())
            return;
        FileOutputStream outputStream = null;
        FileInputStream inputStream = null;
        try {
            outputStream = new FileOutputStream(out);
            inputStream = new FileInputStream(src);
            byte[] bytes = new byte[1024];
            int num = 0;
            while ((num = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, num);
                outputStream.flush();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getRealFilePath(Context context, Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (TextUtils.isEmpty(scheme)){
            data = uri.getPath();
        }else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
            if (data == null) {
                data = getImageAbsolutePath(context, uri);
            }
        }
        return data;
    }
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    public static String getImageAbsolutePath(Context context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.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)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } 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);
            }
        } // 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();
        }
        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);
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值