package com.mq.mylibrary.tool;

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by zrl on 2017/2/17.
 */

public class FileTool {
    //读取指定目录下的所有TXT文件的文件内容
    public static String getFileContent(File file) {
        StringBuilder content = new StringBuilder();
        if (file.isDirectory()) {    //检查此路径名的文件是否是一个目录(文件夹)
            Log.i("File", "The File doesn't not exist "
                    + file.getName() + file.getPath());
        } else {
            if (file.getName().endsWith(".txt")) {//文件格式为txt文件
                BufferedReader buffreader = null;
                String line = null;
                try {
                    buffreader = new BufferedReader(new FileReader(file));
                    //分行读取
                    while ((line = buffreader.readLine()) != null) {
                        content.append(line).append("\n");
                    }
                } catch (java.io.FileNotFoundException e) {
                    Log.d("TestFile", "The File doesn't not exist.");
                } catch (IOException e) {
                    Log.d("TestFile", e.getMessage());
                }
            }
        }
        return content.toString();
    }


    /**
     * 获取根目录指定文件的内容
     */
    public static String getFileContent(String fileName) {
        String result = null;
        try {
            File file = new File(Environment.getExternalStorageDirectory(), fileName);
            /* FileInputSteam 输入流的对象， */
            FileInputStream fis = new FileInputStream(file);
            /* 准备一个字节数组用户装即将读取的数据 */
            byte[] buffer = new byte[fis.available()];
            /* 开始进行文件的读取 */
            fis.read(buffer);
            /* 关闭流  */
            fis.close();
            result = new String(buffer);
        } catch (Exception e) {
            LogTool.e(e.toString());
        }
        return result;
    }

    /**
     * 写入txt文本到SD卡
     */
    public static boolean writeTxt(String name, String content) {
        boolean b = false;
        try {
            //新建文件
            File saveFile = new File(Environment.getExternalStorageDirectory(), name);

            if (!saveFile.exists()) {
                saveFile.createNewFile();
            }
            // FileOutputStream outStream =null;
            //outStream = new FileOutputStream(saveFile);

            FileOutputStream outStream = new FileOutputStream(saveFile);

            outStream.write(content.getBytes());
            outStream.close();
            //outStream.write("测试写入文件".getBytes());
            //outStream.close();
            LogTool.i("写入成功");
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

}
