package com.emato.ich.utils;


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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 默认会找/data/data/包名/file目录下的文件
 * MODE:
 *   MODE_PRIVATE: 默认操作模式, 代表是有数据,写入会覆盖写入       0
 *   MODE_APPEND: 会校验文件是否存在, 存在则追加写入, 不存在则创建  32768
 *   MODE_WORLD_READABLE: 当前文件可以被其他应用读取             1
 *   MODE_WORLD_WRITEABLE: 当前文件可以被其他应用写入            2
 */
public class FileUtils {

    public static final String TAG = "FileUtils";
    private static final String path = "";

    public static void write(String fileName, String content, Context context, int mode){

        try (FileOutputStream outputStream = context.openFileOutput(fileName, mode)) {
            outputStream.write(content.getBytes());
        } catch (FileNotFoundException e) {
            Log.e(TAG, "write: 该路径下没有这个文件!", e);
            LoggingUtils.sendErrorLog("业务异常: 该路径下没有这个文件! ", e);
        } catch (IOException e) {
            Log.e(TAG, "write: 写入文件失败!", e);
            LoggingUtils.sendErrorLog("业务异常: 写入文件失败! ", e);
        }
    }

    public static String read(String fileName, Context context) {

        try (FileInputStream inputStream = context.openFileInput(fileName)) {
            byte[] bytes = new byte[1024];
            StringBuilder builder = new StringBuilder();
            int len = 0;
            while((len = inputStream.read(bytes)) > 0) {
                builder.append(new String(bytes, 0, len));
            }
            return builder.toString();
        } catch (FileNotFoundException e) {
            Log.e(TAG, "read: 读取的文件未找到! ", e);
            LoggingUtils.sendErrorLog("业务异常: 读取的文件未找到! ", e);
        } catch (IOException e) {
            Log.e(TAG, "read: 读取文件出现异常!", e);
            LoggingUtils.sendErrorLog("业务异常: 读取文件出现异常! ", e);
        }
        return "";
    }
}
