FileUtils.java 1.45 KB
package cn.com.glsx.entmicro.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author zhouhaibao
 * @version 1.0
 * @description: 读取文件流
 * @date 2021/11/12 10:41
 */
public class FileUtils {

    /**
     * 根据url下载文件流
     *
     * @param urlStr
     * @return
     */
    public static InputStream getInputStreamFromUrl(String urlStr) {
        InputStream inputStream = null;
        try {
            //url解码
            URL url = new URL(java.net.URLDecoder.decode(urlStr, "UTF-8"));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            inputStream = conn.getInputStream();
        } catch (IOException e) {
            e.getStackTrace();
        }
        return inputStream;
    }

    /**
     * 获取文件扩展名
     *
     * @return
     */
    public static String getFileType(String filePath) {
        if(filePath.lastIndexOf(".") != -1 && filePath.lastIndexOf(".") != 0){
            return filePath.substring(filePath.lastIndexOf("."));
        }
        return "";
    }
}