FileUtil 常用IO流操作

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;

import com.sgcc.wsgw.publiclibrary.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by HuangXing on 2018/4/27.
 */

public class FileUtil {

    /**
     * 创建File
     *
     * @param dir
     * @param fileName
     * @return
     */
    public static File createFile(String dir, String fileName) {
        File fileDir = new File(dir);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File file = new File(fileDir, fileName);
        return file;

    }

    /**
     * 获取File
     *
     * @param dir
     * @param fileName
     * @return
     */
    public static File getFile(String dir, String fileName) {
        File fileDir = new File(dir);
        File file = null;
        if (fileDir.exists()) {
            file = new File(fileDir, fileName);
            if (file.exists()) {
                return file;
            } else {
                return null;
            }
        }
        return file;
    }

    /**
     * 获取File
     *
     * @param filePath
     * @return
     */
    public static File getFile(String filePath) {
        if (CommonUtil.isEmpty(filePath)) {
            return null;
        }
        File file = new File(filePath);
        if (file.exists()) {
            return file;
        }
        return null;
    }

    /**
     * 删除旧文件
     *
     * @param old
     */
    public static void deleteFile(File old) {
        if (old.exists()) {
            if (old.isFile()) {//判断是否是文件
                old.delete();
            } else if (old.isDirectory()) {//否则如果它是一个目录
                File files[] = old.listFiles();//声明目录下所有的文件
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);//把每个文件
                }
            }
            old.delete();
        }
    }

    /**
     * SD卡是否可用.
     */
    public static boolean sdCardIsAvailable() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }

    /**
     * 得到SD卡根目录路径.
     */
    public static String getRootPath(Context context) {
        if (FileUtil.sdCardIsAvailable()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath(); // 取得sdcard文件路径
        } else {
            return context.getFilesDir().getAbsolutePath();
        }
    }


    /**
     *  * 将dir1下的文件复制到dir2下面的
     *  *
     *  * @param dir1
     *  * @param fileName1
     *  * @param dir2
     *  * @param fileName2
     *  
     */
    public static void saveFile1(String dir1, String fileName1, String dir2, String fileName2) {
        File file1 = getFile(dir1, fileName1);
        File file2 = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        if (file1 != null && file1.exists()) {
            try {
                bis = new BufferedInputStream(new FileInputStream(file1));
                file2 = createFile(dir2, fileName2);
                bos = new BufferedOutputStream(new FileOutputStream(file2));
                byte[] buffer = new byte[1024 * 4];
                int len = -1;
                while ((len = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeIO(bos);
                closeIO(bis);
            }
        }
    }

    /**
     * 将流文件保存到内部存储中
     *
     * @param fileName
     * @param is
     */
    public static boolean saveFile(String dir, String fileName, InputStream is) {
        File file = createFile(dir, fileName);
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024 * 4];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.flush();
            Logout.e("保存文件成功,文件路径保存在:" + fileName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            closeIO(bis);
            closeIO(fos);
            closeIO(bos);
        }
    }

    /**
     *  * 方式1:BufferedReader
     *  * InputStream中保存的字节流转化成Sring(文本型字段)
     *  *
     *  * @param is
     *  * @return
     *  
     */
    public static String readJsonStr1(InputStream is) {
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedReader br = new BufferedReader(new InputStreamReader(bis));
        StringBuilder stringBuilder = new StringBuilder();
        try {
            String str = "";
            while ((str = br.readLine()) != null) {
                stringBuilder.append(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeIO(is);
            closeIO(bis);
            closeIO(br);
        }
        return stringBuilder.toString();
    }


    /**
     * 将string类型的文件读取出来
     * 读取json类型的文本文件
     *
     * @param dir
     * @param fileName
     * @return
     */
    public static String readStringFile(String dir, String fileName) {
        String content = null;
        File file = getFile(dir, fileName);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        if (file != null && file.exists()) {
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024 * 4];
                int len = -1;
                while ((len = (bis.read(buffer))) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
                content = bos.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeIO(bis);
                closeIO(fis);
                closeIO(bos);
            }
        } else {
            return null;
        }
        return content;
    }

    /**
     *  * String
     *  * 将文本写入到内部存储中
     *  *
     *  * @param context
     *  * @param fileName 命名fileName
     *  
     */
    public static void writeFile(Context context, String fileName) {
        String s = "在内部存储写一个txt测试测试";
        try {
            FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            byte[] bytes = s.getBytes();
            bos.write(bytes);
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     *  * 将外部的文件保存到内部存储中
     *  *
     *  * @param context
     *  * @param fileName
     *  * @param is
     *  
     */
    public static void copyInFile(Context context, String fileName, InputStream is) {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            bos = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024 * 2];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeIO(bis);
            closeIO(fos);
            closeIO(bos);
        }
    }


    /**
     *  * 获取InputStream
     *  
     */
    public InputStream getInputStream(Context context, int id, File file, String urlAddress) {
        InputStream inputStream = null;


        try {
            //资源文件
            inputStream = context.getAssets().open("test.json");//从assent下面的资源文件
            inputStream = context.getResources().openRawResource(R.raw.test);//获取raw下面的资源文件


            // 从本地file下面获取资源
            inputStream = new FileInputStream(file);


            //从网络上获取
            URL url = new URL(urlAddress);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            inputStream = connection.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return inputStream;
    }


    /**
     * 向文件中写入数据
     *
     * @param filePath 目标文件全路径
     * @param data     要写入的数据
     * @return true表示写入成功  false表示写入失败
     */
    public static boolean writeBytes(String filePath, byte[] data) {
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(data);
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 从文件中读取数据
     *
     * @param file
     * @return
     */
    public static byte[] readBytes(String file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            int len = fis.available();
            byte[] buffer = new byte[len];
            fis.read(buffer);
            fis.close();
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 向文件中写入字符串String类型的内容
     *
     * @param file    文件路径
     * @param content 文件内容
     * @param charset 写入时候所使用的字符集
     */
    public static void writeString(String file, String content, String charset) {
        try {
            byte[] data = content.getBytes(charset);
            writeBytes(file, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从文件中读取数据,返回类型是字符串String类型
     *
     * @param file    文件路径
     * @param charset 读取文件时使用的字符集,如utf-8、GBK等
     * @return
     */
    public static String readString(String file, String charset) {
        byte[] data = readBytes(file);
        String ret = null;

        try {
            ret = new String(data, charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            int length = in.read(bytes);
            closeIO(in);
            base64 = Base64.encodeToString(bytes, 0, length, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64;
    }

    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * base64字符串转文件
     *
     * @param base64
     * @return
     */
    public static File base64ToFile(String savePath, String name, String base64) {
        if (CommonUtil.isEmpty(savePath)) {
            savePath = Environments.getRootPath();
        }
        File file = createFile(savePath, name);
        FileOutputStream out = null;
        try {
            // 解码,然后将字节转换为文件
            byte[] bytes = Base64.decode(base64, Base64.DEFAULT);// 将字符串转换为byte数组
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            byte[] buffer = new byte[1024];
            out = new FileOutputStream(file);
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread); // 文件写操作
            }
            out.flush();
        } catch (Exception ioe) {
            ioe.printStackTrace();
            return null;
        } finally {
            closeIO(out);
        }
        return file;
    }

    /**
     * 保存文件到某个路径下面
     *
     * @param fromFile
     * @param tofile
     */
    public static boolean CopySdcardFile(String fromFile, String tofile) {
        if (CommonUtil.isEmpty(fromFile))
            return false;
        File file = new File(fromFile);
        if (!file.exists())
            return false;
        try {
            FileInputStream fis = new FileInputStream(fromFile);
            FileOutputStream fos = new FileOutputStream(tofile);
            byte[] buffer = new byte[1024 * 2];
            int len = -1;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param @param  bitmap
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: bitmapToBase64
     * @Description: TODO(Bitmap 转换为字符串)
     */

    @SuppressLint("NewApi")
    public static String bitmapToBase64(Bitmap bitmap) {

        // 要返回的字符串
        String reslut = null;

        ByteArrayOutputStream baos = null;

        try {

            if (bitmap != null) {

                baos = new ByteArrayOutputStream();
                /**
                 * 压缩只对保存有效果bitmap还是原来的大小
                 */
                bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);

                baos.flush();
                baos.close();
                // 转换为字节数组
                byte[] byteArray = baos.toByteArray();

                // 转换为字符串
                reslut = Base64.encodeToString(byteArray, Base64.DEFAULT);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return reslut;

    }

    /**
     * @param @param  base64String
     * @param @return 设定文件
     * @return Bitmap    返回类型
     * @throws
     * @Title: base64ToBitmap
     * @Description: TODO(base64l转换为Bitmap)
     */
    public static Bitmap base64ToBitmap(String base64String) {

        byte[] decode = Base64.decode(base64String, Base64.DEFAULT);

        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);

        return bitmap;
    }

    public static void closeIO(Closeable closeable) {
        try {
            if (closeable != null)
                closeable.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值