package org.dromara.settlement.common.file;

import org.dromara.common.core.utils.StringUtils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Base64;


public class FileUtils {
	public static String base64ToFile(String base64, String fileName, String savePath) {
		File file = null;
		// 创建文件目录
		String filePath = savePath;
		File dir = new File(filePath);
		if (!dir.exists() && !dir.isDirectory()) {
			dir.mkdirs();
		}
		BufferedOutputStream bos = null;
		java.io.FileOutputStream fos = null;
		try {
			byte[] bytes = Base64.getDecoder().decode(base64);
			filePath = filePath + fileName;
			file = new File(filePath);
			fos = new java.io.FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			filePath = "";
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return filePath;
	}

	/**
	 * 读取txt文件
	 * @author 张涛
	 * @date 2022年8月3日
	 * @param filePath
	 * @param rowSeparator 行分隔符
	 * @return
	 */
	public static String readTxtFile(String filePath,String rowSeparator) {

		File file = new File(filePath);
        if(file.isFile() && file.exists()){
        	if(StringUtils.isBlank(rowSeparator)) {
        		rowSeparator = "";
        	}
        	FileInputStream fileInputStream = null;
        	InputStreamReader inputStreamReader = null;
        	BufferedReader bufferedReader = null;
            try {
                fileInputStream = new FileInputStream(file);
                inputStreamReader = new InputStreamReader(fileInputStream);
                bufferedReader = new BufferedReader(inputStreamReader);
                StringBuffer sb = new StringBuffer();
                String text = null;
                while((text = bufferedReader.readLine()) != null){
                    sb.append(text+rowSeparator);
                }
                return sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
            	try {
            		if(bufferedReader != null)
            			bufferedReader.close();
            		if(inputStreamReader != null)
            			inputStreamReader.close();
            		if(fileInputStream != null)
            			fileInputStream.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
            }
        }
        return "";
	}
}
