package com.ym.mec.util.file;


import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {

    public static String getFileExpandByPath(String filePath) {
        int i = filePath.lastIndexOf(".");
        if (i > 0) {
            return filePath.substring(i+1);
        }
        return "";
    }

    public static File multipartFileToFile(MultipartFile file) {
        File toFile = null;
        InputStream ins = null;
        try {
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return toFile;
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
