首页 > 系统 > Android > 正文

Android 文件操作工具类

2019-11-06 10:05:33
字体:
来源:转载
供稿:网友
file工具类,文件操作工具类,解压压缩包
package com.utils;import android.annotation.SupPRessLint;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.os.storage.StorageManager;import android.util.Base64;import android.util.Log;import com.kailashtech.core.TC2CConstant;import org.apache.http.Header;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.lang.reflect.Array;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.math.BigInteger;import java.security.MessageDigest;import java.util.ArrayList;import java.util.List;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;public class FileTools {    private static FileOutputStream fs;    public FileTools() {    }    /**     * DeCompress the ZIP to the path     *     * @param zipFileString name of ZIP     * @param outPathString path to be unZIP     * @throws Exception     */    public static void UnZipFolder(String zipFileString, String outPathString) throws Exception {        Log.d(TC2CConstant._SystemLogTag, "zipFileString:" + zipFileString);        Log.d(TC2CConstant._SystemLogTag, "outPathString:" + outPathString);        if (!new File(outPathString).exists())            new File(outPathString).mkdirs();        ZipInputStream inZip = new ZipInputStream(new FileInputStream(zipFileString));        ZipEntry zipEntry;        String szName = "";        System.out.println("start");        while ((zipEntry = inZip.getNextEntry()) != null) {            szName = zipEntry.getName();            System.out.println(szName);            if (zipEntry.isDirectory()) {                // get the folder name of the widget                 szName = szName.substring(0, szName.length() - 1);                File folder = new File(outPathString + File.separator + szName);                folder.mkdirs();            } else {                File file = new File(outPathString + File.separator + szName);                file.createNewFile();                // get the output stream of the file                 FileOutputStream out = new FileOutputStream(file);                int len;                byte[] buffer = new byte[1024];                // read (len) bytes into buffer                 while ((len = inZip.read(buffer)) != -1) {                    // write (len) byte from buffer at the position 0                     out.write(buffer, 0, len);                    out.flush();                }                out.close();            }        }        Log.d(TC2CConstant._SystemLogTag, "unzip OK");        inZip.close();    }    public static void UnZipAssetFolder(String assetFile, String outPathString, Context con) throws Exception {        Log.d(TC2CConstant._SystemLogTag, "zipAssetFile:" + assetFile);        Log.d(TC2CConstant._SystemLogTag, "outPathString:" + outPathString);        if (!new File(outPathString).exists())            new File(outPathString).mkdirs();        InputStream in;        in = con.getResources().getAssets().open(assetFile);        ZipInputStream inZip = new ZipInputStream(in);        ZipEntry zipEntry;        String szName = "";        System.out.println("start");        while ((zipEntry = inZip.getNextEntry()) != null) {            szName = zipEntry.getName();            System.out.println(szName);            if (zipEntry.isDirectory()) {                // get the folder name of the widget                 szName = szName.substring(0, szName.length() - 1);                File folder = new File(outPathString + File.separator + szName);                folder.mkdirs();            } else {                File file = new File(outPathString + File.separator + szName);                file.createNewFile();                // get the output stream of the file                 FileOutputStream out = new FileOutputStream(file);                int len;                byte[] buffer = new byte[1024];                // read (len) bytes into buffer                 while ((len = inZip.read(buffer)) != -1) {                    // write (len) byte from buffer at the position 0                     out.write(buffer, 0, len);                    out.flush();                }                out.close();            }        }        Log.d(TC2CConstant._SystemLogTag, "unzip OK");        inZip.close();    }    /**     * Compress file and folder     *     * @param srcFileString file or folder to be Compress     * @param zipFileString the path name of result ZIP     * @throws Exception     */    public static void ZipFolder(String srcFileString, String zipFileString) throws Exception {        //create ZIP        ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));        //create the file        File file = new File(srcFileString);        //compress        ZipFiles(file.getParent() + File.separator, file.getName(), outZip);        //finish and close        outZip.finish();        outZip.close();    }    /**     * compress files     *     * @param folderString     * @param fileString     * @param zipOutputSteam     * @throws Exception     */    private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {        if (zipOutputSteam == null)            return;        File file = new File(folderString + fileString);        if (file.isFile()) {            ZipEntry zipEntry = new ZipEntry(fileString);            FileInputStream inputStreamTemp = new FileInputStream(file);            zipOutputSteam.putNextEntry(zipEntry);            int len;            byte[] buffer = new byte[4096];            while ((len = inputStreamTemp.read(buffer)) != -1) {                zipOutputSteam.write(buffer, 0, len);            }            inputStreamTemp.close();            zipOutputSteam.closeEntry();        } else {            //folder            String fileList[] = file.list();            //no child file and compress             if (fileList.length <= 0) {                ZipEntry zipEntry = new ZipEntry(fileString + File.separator);                zipOutputSteam.putNextEntry(zipEntry);                zipOutputSteam.closeEntry();            }            //child files and recursion             for (int i = 0; i < fileList.length; i++) {                ZipFiles(folderString, fileString + java.io.File.separator + fileList[i], zipOutputSteam);            }//end of for         }    }    /**     * return the InputStream of file in the ZIP     *     * @param zipFileString name of ZIP     * @param fileString    name of file in the ZIP     * @return InputStream     * @throws Exception     */    public static InputStream UpZip(String zipFileString, String fileString) throws Exception {        ZipFile zipFile = new ZipFile(zipFileString);        ZipEntry zipEntry = zipFile.getEntry(fileString);        return zipFile.getInputStream(zipEntry);    }    /**     * return files list(file and folder) in the ZIP     *     * @param zipFileString  ZIP name     * @param bContainFolder contain folder or not     * @param bContainFile   contain file or not     * @return     * @throws Exception     */    public static List<File> GetFileList(String zipFileString, boolean bContainFolder, boolean bContainFile) throws Exception {        List<File> fileList = new ArrayList<File>();        ZipInputStream inZip = new ZipInputStream(new FileInputStream(zipFileString));        ZipEntry zipEntry;        String szName = "";        while ((zipEntry = inZip.getNextEntry()) != null) {            szName = zipEntry.getName();            if (zipEntry.isDirectory()) {                // get the folder name of the widget                 szName = szName.substring(0, szName.length() - 1);                File folder = new File(szName);                if (bContainFolder) {                    fileList.add(folder);                }            } else {                File file = new File(szName);                if (bContainFile) {                    fileList.add(file);                }            }        }        inZip.close();        return fileList;    }    //写数据    public static void writeFile(String fileName, String writestr) {        try {            OutputStream os = new FileOutputStream(fileName);            os.write(writestr.getBytes(), 0, writestr.getBytes().length);            // 完毕,关闭所有链接            os.close();        } catch (Exception ignored) {        }    }    //读数据    public static String readFile(String fileName) {        String res = "";        try {            InputStream os = new FileInputStream(fileName);            StringBuffer sb = new StringBuffer();            byte[] b = new byte[1024];            int len = 0;            try {                while ((len = os.read(b)) != -1) {                    sb.append(new String(b, 0, len, "utf-8"));                }                res = sb.toString();            } catch (IOException e) {                e.printStackTrace();            }        } catch (Exception ignored) {        }        return res;    }    //下载文件    @SuppressLint("DefaultLocale")    public static String downLoadFile(String downLoadUrl, String saveFile, String md5Str) {        Log.d(TC2CConstant._SystemLogTag, "downLoadUrl: " + downLoadUrl);        Log.d(TC2CConstant._SystemLogTag, "saveFile: " + saveFile);        //准备拼接新的文件名(保存在存储卡后的文件名)        File file = new File(saveFile);        //如果目标文件已经存在,则删除。产生覆盖旧文件的效果        if (file.exists()) {            file.delete();        }        try {            HttpGet get = new HttpGet(downLoadUrl);//			get.addHeader("If-Match",md5Str.toUpperCase());            Log.d(TC2CConstant._SystemLogTag, "get begin ! ");            HttpResponse response = new DefaultHttpClient().execute(get);            if (response.getStatusLine().getStatusCode() == 200) {                //处理成功的json数据                Log.d(TC2CConstant._SystemLogTag, "Http Recv OK");                byte[] bs = EntityUtils.toByteArray(response.getEntity());                Header[] headers = response.getAllHeaders();                String ETag = "";                for (int i = 0; i < headers.length; i++) {                    if (headers[i].getName().equals("ETag")) {                        ETag = headers[i].getValue().toUpperCase();                        Log.d(TC2CConstant._SystemLogTag, headers[i].getName() + " == " + ETag);                    }                }                OutputStream os = new FileOutputStream(saveFile);                os.write(bs, 0, bs.length);                // 完毕,关闭所有链接                os.close();                String fileMd5Str = getFileMD5(file).toUpperCase();                Log.d(TC2CConstant._SystemLogTag, "fileMd5Str = " + fileMd5Str);                fileMd5Str = "/"" + fileMd5Str + "/"";                if (fileMd5Str.equalsIgnoreCase(ETag)) {                    Log.d(TC2CConstant._SystemLogTag, "md5Check OK ");                    return saveFile;                } else {                    Log.d(TC2CConstant._SystemLogTag, "md5Check ERROR ");                    return "";                }            } else {                Log.d(TC2CConstant._SystemLogTag, " response.getStatusLine().getStatusCode()= " + response.getStatusLine().getStatusCode());                return "";            }        } catch (Exception e) {            e.printStackTrace();            return "";        }    }    //根据全路径读取文件内容    public static String ReadTxtFile(String strFilePath) {        String path = strFilePath;        String content = ""; //文件内容字符串        //打开文件        File file = new File(path);        //如果path是传递过来的参数,可以做一个非目录的判断        if (file.isDirectory()) {            Log.d("TestFile", "The File doesn't not exist.");        } else {            try {                InputStream instream = new FileInputStream(file);                if (instream != null) {                    InputStreamReader inputreader = new InputStreamReader(instream);                    BufferedReader buffreader = new BufferedReader(inputreader);                    String line;                    //分行读取                    while ((line = buffreader.readLine()) != null) {                        content += line + "/n";                    }                    instream.close();                }            } catch (java.io.FileNotFoundException e) {                Log.d("TestFile", "The File doesn't not exist.");            } catch (IOException e) {                Log.d("TestFile", e.getMessage());            }        }        return content;    }    public static boolean deleteFile(String saveFile) {        Log.d(TC2CConstant._SystemLogTag, "deleteFile: " + saveFile);        //准备拼接新的文件名(保存在存储卡后的文件名)        File file = new File(saveFile);        //如果目标文件已经存在,则删除。        if (file.exists()) {            file.delete();            Log.d(TC2CConstant._SystemLogTag, "delete OK: " + saveFile);            return true;        } else {            return false;        }    }    public static String bitmapToBase64(Bitmap bitmap) {        String result = null;        ByteArrayOutputStream baos = null;        try {            if (bitmap != null) {                baos = new ByteArrayOutputStream();                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);                baos.flush();                baos.close();                byte[] bitmapBytes = baos.toByteArray();                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (baos != null) {                    baos.flush();                    baos.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }        return result;    }    public static Bitmap zoomImage(Bitmap bgimage, int newHeight) {        // 获取这个图片的宽和高        float width = bgimage.getWidth();        float height = bgimage.getHeight();        if (height > newHeight && newHeight > 0) {            // 创建操作图片用的matrix对象            Matrix matrix = new Matrix();            // 计算宽高缩放率            float scaleHeight = ((float) newHeight) / width;            // 缩放图片动作            matrix.postScale(scaleHeight, scaleHeight);            bgimage = Bitmap.createBitmap(bgimage, 0, 0, (int) width,                    (int) height, matrix, true);            return bgimage;        } else {            return bgimage;        }    }    public static void saveBitmapFile(Bitmap bitmap, String filePath) {        File file = new File(filePath);//将要保存图片的路径        try {            file.delete();            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);            bos.flush();            bos.close();        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 基于质量的压缩算法, 此方法未 解决压缩后图像失真问题     * <br> 可先调用比例压缩适当压缩图片后,再调用此方法可解决上述问题     *maxBytes 压缩后的图像最大大小 单位为byte     */    public static Bitmap compressBitmap(Bitmap bitmap, int options) {        try {            ByteArrayOutputStream baos = new ByteArrayOutputStream();            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);            byte[] bts = baos.toByteArray();            bitmap = BitmapFactory.decodeByteArray(bts, 0, bts.length);            baos.close();            return bitmap;        } catch (IOException e) {            e.printStackTrace();            return null;        }    }    /**     * 获取单个文件的MD5值!     *     * @param file     * @return     */    public static String getFileMD5(File file) {        if (!file.isFile()) {            return null;        }        MessageDigest digest = null;        FileInputStream in = null;        byte buffer[] = new byte[1024];        int len;        try {            digest = MessageDigest.getInstance("MD5");            in = new FileInputStream(file);            while ((len = in.read(buffer, 0, 1024)) != -1) {                digest.update(buffer, 0, len);            }            in.close();        } catch (Exception e) {            e.printStackTrace();            return null;        }        BigInteger bigInt = new BigInteger(1, digest.digest());        String md5Str = bigInt.toString(16);        String fixStr = "00000000000000000000000000000000";        md5Str = fixStr.substring(md5Str.length()) + md5Str;        return md5Str;    }    //下载文件    public static String getHeadFile(String headPath, int size, int userId, Context ctx) {        String downLoadUrl = getHeadFileUrl(headPath, size);        Log.d(TC2CConstant._SystemLogTag, "downLoadUrl: " + downLoadUrl);        String dirName = ctx.getFilesDir() + "/zykHeadFile/";        File f = new File(dirName);        if (!f.exists()) {            f.mkdir();        }        String saveFile = dirName + userId;        Log.d(TC2CConstant._SystemLogTag, "saveFile: " + saveFile);        //准备拼接新的文件名(保存在存储卡后的文件名)        File file = new File(saveFile);        //如果目标文件已经存在,则删除。产生覆盖旧文件的效果        if (file.exists()) {            Log.d(TC2CConstant._SystemLogTag, "Already Have: " + downLoadUrl);            file.delete();//			return saveFile;        } else {            Log.d(TC2CConstant._SystemLogTag, "get begin:" + downLoadUrl);        }        try {            HttpGet get = new HttpGet(downLoadUrl);            HttpResponse response = new DefaultHttpClient().execute(get);            if (response.getStatusLine().getStatusCode() == 200) {                //处理成功的json数据                Log.d(TC2CConstant._SystemLogTag, "Http Recv OK");                byte[] bs = EntityUtils.toByteArray(response.getEntity());                Header[] headers = response.getAllHeaders();                String ETag = "";                for (int i = 0; i < headers.length; i++) {                    if (headers[i].getName().equals("ETag")) {                        ETag = headers[i].getValue();                        Log.d(TC2CConstant._SystemLogTag, headers[i].getName() + " == " + ETag);                    }                }                OutputStream os = new FileOutputStream(saveFile);                os.write(bs, 0, bs.length);                // 完毕,关闭所有链接                os.close();                Log.d(TC2CConstant._SystemLogTag, "File Save OK :" + saveFile);                return saveFile;            } else {                Log.d(TC2CConstant._SystemLogTag, " response.getStatusLine().getStatusCode()= " + response.getStatusLine().getStatusCode());                return "";            }        } catch (Exception e) {            e.printStackTrace();            return "";        }    }    //获取头像文件路径    public static String getHeadFileUrl(String headPath, int size) {        String url = "http://cdn.ziyoke.com/" + headPath;        if (size > 0) {            url += "@" + size + "w_" + size + "h_2e";        }        return url;    }    public static void copyFile(String oldPath, String newPath) {        try {            int bytesum = 0;            int byteread = 0;            File oldfile = new File(oldPath);            if (!oldfile.exists()) { //文件不存在时                  InputStream inStream = new FileInputStream(oldPath); //读入原文件                   fs = new FileOutputStream(newPath);                byte[] buffer = new byte[1444];                while ((byteread = inStream.read(buffer)) != -1) {                    bytesum += byteread; //字节数 文件大小                       System.out.println(bytesum);                    fs.write(buffer, 0, byteread);                }                Log.d(TC2CConstant._SystemLogTag, "复制文件成功 :" + oldPath + ":" + newPath);                inStream.close();            } else {                FileInputStream fosfrom = new FileInputStream(oldfile);                fs = new FileOutputStream(newPath);                byte bt[] = new byte[1024];                int c;                while ((c = fosfrom.read(bt)) > 0) {                    fs.write(bt, 0, c); //将内容写到新文件当中                }                fosfrom.close();                fs.close();                Log.d(TC2CConstant._SystemLogTag, "复制文件成功 :" + oldPath + ":" + newPath);            }        } catch (Exception e) {            Log.d(TC2CConstant._SystemLogTag, "复制文件出错 :" + oldPath);            e.printStackTrace();        }    }    /**     * 解压Assets中的文件     * @param context 上下文对象     * @param assetName 压缩包文件名     * @param outputDirectory 输出目录     * @throws IOException     */    public static void unZip(Context context, String assetName,String outputDirectory) throws IOException {        File file1 = new File(FileTools.getStoragePath(context, false) + "/" + assetName);        //创建解压目标目录        File file = new File(outputDirectory);        //如果目标目录不存在,则创建        if (!file.exists()) {            file.mkdirs();        }        InputStream inputStream = null;        inputStream=new FileInputStream(file1);        //打开压缩文件//        inputStream = context.getAssets().open(assetName);        ZipInputStream zipInputStream = new ZipInputStream(inputStream);        //读取一个进入点        ZipEntry zipEntry = zipInputStream.getNextEntry();        //使用1Mbuffer        byte[] buffer = new byte[1024 * 1024];        //解压时字节计数        int count = 0;        //如果进入点为空说明已经遍历完所有压缩包中文件和目录        while (zipEntry != null) {            //如果是一个目录            if (zipEntry.isDirectory()) {                //String name = zipEntry.getName();                //name = name.substring(0, name.length() - 1);                file = new File(outputDirectory + File.separator + zipEntry.getName());                file.mkdir();            } else {                //如果是文件                file = new File(outputDirectory + File.separator                        + zipEntry.getName());                //创建该文件                file.createNewFile();                FileOutputStream fileOutputStream = new FileOutputStream(file);                while ((count = zipInputStream.read(buffer)) > 0) {                    fileOutputStream.write(buffer, 0, count);                }                fileOutputStream.close();            }            //定位到下一个文件入口            zipEntry = zipInputStream.getNextEntry();        }        zipInputStream.close();    }    /**     *     * @param mContext     * @param is_removale  参数 is_removable为false时得到的是内置sd卡路径,为true则为外置sd卡路径。     * @return 返回储存卡路径     */    public static String getStoragePath(Context mContext, boolean is_removale) {        StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);        Class<?> storageVolumeClazz = null;        try {            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");            Method getPath = storageVolumeClazz.getMethod("getPath");            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");            Object result = getVolumeList.invoke(mStorageManager);            final int length = Array.getLength(result);            for (int i = 0; i < length; i++) {                Object storageVolumeElement = Array.get(result, i);                String path = (String) getPath.invoke(storageVolumeElement);                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);                if (is_removale == removable) {                    return path;                }            }        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (InvocationTargetException e) {            e.printStackTrace();        } catch (NoSuchMethodException e) {            e.printStackTrace();        } catch (IllegalaccessException e) {            e.printStackTrace();        }        return null;    }    /**     * 根据名称在sd卡查找指定压缩文件     * @param file sd卡路径     * @param keyWord 文件名称     * @param isDelete true表示找到后删除     * @return 返回压缩文件路径     */    public static String findFile(File file, String keyword,boolean isDelete) {        String res = "";        if (!file.isDirectory()) {            res = "不是目录";            return res;        }        File[] files = new File(file.getPath()).listFiles();        boolean delete=false;        for (File f : files) {            if (f.getName().indexOf(keyword) >= 0) {                res += f.getPath();                if (isDelete) {                    delete = f.delete();                }            }        }        if (res.equals("")) {            res = "没有找到相关文件";        }        return res;    }    /**     * 获取Assets目录下的文件路径     * @param context     * @param fileName     * @return     */    public static String getAssetsCacheFile(Context context,String fileName)   {        File cacheFile = new File(context.getCacheDir(), fileName);        try {            InputStream inputStream = context.getAssets().open(fileName);            try {                FileOutputStream outputStream = new FileOutputStream(cacheFile);                try {                    byte[] buf = new byte[1024];                    int len;                    while ((len = inputStream.read(buf)) > 0) {                        outputStream.write(buf, 0, len);                    }                } finally {                    outputStream.close();                }            } finally {                inputStream.close();            }        } catch (IOException e) {            e.printStackTrace();        }        return cacheFile.getAbsolutePath();    }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表