package com.docus.server.common.util;

import com.docus.core.util.Func;

import java.io.*;

/**
 * 文件工具
 *
 * @author WYBDEV
 */
public class FileUtil {
    /**
     * @return 取得当前jar路径
     */
    public static String currentPath() {
        try {
            File dir = new File(".");
            return dir.getCanonicalPath();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 根据文件对象，创建上级目录
     *
     * @param file 文件
     * @return 创建结果
     */
    public static boolean mkFileDirs(File file) {
        if (!file.getParentFile().exists()) {
            return file.getParentFile().mkdirs();
        }
        return true;
    }

    /**
     * 保存字符数据至文件
     *
     * @param data 数据
     * @param file 保存的文件
     */
    public static void saveStrData(String data, File file) {
        mkFileDirs(file);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            fileWriter.write(data);
            fileWriter.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String path = currentPath() + File.separator + "remotecall" + File.separator + Func.randomUUID() + ".txt";
        File file = new File(path);
        saveStrData("随便写一点东西", file);
        String where = readStr(file);
        System.out.println(where);
    }

    public static String readStr(File file) {
        BufferedReader bufferedReader = null;
        try {
            StringBuilder sb = new StringBuilder();
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception ex){
            ex.printStackTrace();
            return null;
        }finally {
            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
