FileUtil 常用IO流操作

package com.example.iotest.utils;


import android.content.Context;
import android.os.Environment;
import android.util.Log;


import com.example.iotest.R;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
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.net.HttpURLConnection;
import java.net.URL;


/**
 * Created by liukang on 2017/11/6 16:11.
 */


public class FileUtil {


    /**
     * 将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 {
                CloseStreamUtils.close(bos);
                CloseStreamUtils.close(bis);
            }
        }
    }




    /**
     * 将InputStream 保存到 dir 下面
     *
     * @param dir
     * @param fileName
     * @param is
     */
    public static boolean saveFile2(String dir, String fileName, InputStream is) {
        File file = createFile(dir, fileName);
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(new FileOutputStream(file));
            byte[] buffer = new byte[1024 * 4];
            int len = -1;
            while ((len = bis.read(null)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            CloseStreamUtils.close(bis);
            CloseStreamUtils.close(bos);
        }
        return true;
    }


    /**
     * 将String串保存到本地文件
     * @param dir
     * @param fileName
     * @param content
     */
    public static boolean saveStringFile(String dir, String fileName, String content) {
        File file = createFile(dir, fileName);
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            byte[] bytes = content.getBytes();
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            CloseStreamUtils.close(fos);
            CloseStreamUtils.close(bos);
        }
        Log.e("TAG", "保存成功!");
        return true;
    }


    /**
     * 将string类型的文件读取出来
     *
     * @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 {
                CloseStreamUtils.close(bis);
                CloseStreamUtils.close(fis);
                CloseStreamUtils.close(bos);
            }
        } else {
            return null;
        }
        return content;
    }


    /**
     * 方式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 {
            CloseStreamUtils.close(is);
            CloseStreamUtils.close(bis);
            CloseStreamUtils.close(br);
        }
        return stringBuilder.toString();
    }


    /**
     * 读取内部存储信息(文本型的),转化成String
     * @param context
     * @param fileName 内部存储的文件的名称
     * @return
     */
    public static String readFile(Context context, String fileName) {
        ByteArrayOutputStream bos = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            bos = new ByteArrayOutputStream();
            fis = context.openFileInput(fileName);
            bis = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024 * 4];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null)
                    bos.flush();
                CloseStreamUtils.close(fis);
                CloseStreamUtils.close(bis);
                CloseStreamUtils.close(bos);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bos.toString();
    }


    /**
     * 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 {
            CloseStreamUtils.close(bis);
            CloseStreamUtils.close(fos);
            CloseStreamUtils.close(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;
    }




    /**
     * 创建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;
    }




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


    /**
     * SD卡是否可用.
     */
    public static boolean sdCardIsAvailable() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sd = new File(Environment.getExternalStorageDirectory().getPath());
            return sd.canWrite();
        } else
            return false;
    }




}

猜你喜欢

转载自blog.csdn.net/lk2021991/article/details/78468392