java FileUtils 文件地址转换

package com.xiaoai.life.common.utils;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.*;

/**
 * File文件工具类
 * @author 
 */
@SuppressWarnings("restriction")
@Slf4j
public class FileUtils extends FileUtil{
    /**
     * 将网络路径Url转换为MultipartFile
     * @param url
     * @return
     * @throws Exception
//     */
    public static MultipartFile urlToMultipartFile(String url) throws Exception {
        if (StringUtils.isBlank(url)){
            throw new RuntimeException("图片网络路径不能为空");
        }
        log.info("网络路径Url:{}",url);
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
        httpUrl.connect();
        InputStream ins=httpUrl.getInputStream();

        int lastIndexOf = url.lastIndexOf(".");
        MockMultipartFile multipartFile = new MockMultipartFile("file",UUID.randomUUID().toString() + url.substring(lastIndexOf), ContentType.APPLICATION_OCTET_STREAM.toString(),ins);

        ins.close();
        return multipartFile;
    }

    /**
     * 将网络路径Url转换为InputStream
     * @param url
     * @return
     * @throws Exception
     */
    public static InputStream urlToInputStream(String url) throws Exception {
        log.info(url);
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
        httpUrl.connect();
        return httpUrl.getInputStream();
    }

    /**
     * 将网络路径Url转换为byte
     * @param url
     * @return
     * @throws Exception
     */
    public static byte[] urlToByte(String url) throws Exception{
        InputStream inputStream = urlToInputStream(url);//将网络路径Url转换为InputStream
        byte[] bs = inputStreamToBytes(inputStream);//将InputStream转为byte[]
        return bs;
    }

    /**
     * 获取网络路径文件名称
     * 例: https://hb-data.obs.cn-north-9.myhuaweicloud.com/fc7e224a7d944165a16b77065ccbc8d5.jpeg
     * 返回 fc7e224a7d944165a16b77065ccbc8d5.jpeg
     * @param url
     * @return
     */
    public static String getUrlFileName(String url){
        int lastIndexOf = url.lastIndexOf("/")+1;
        String fileName = url.substring(lastIndexOf);
        return fileName;
    }


    /**
     * 将InputStream转为byte[]
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] inputStreamToBytes(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();//内存流如果不再被使用,字节数组会被垃圾回收掉,所以不需要关闭。
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;

        try {
            //使用一个输入流从buffer里把数据读取出来
            while( (len=inStream.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /**
     * 将byte[]转为InputStream
     * @param byt
     * @return
     */
    public static InputStream bytesToInputStream(byte[] byt) {
        InputStream ins = new ByteArrayInputStream(byt);
        return ins;
    }

    /**
     * base64转MultipartFile
     * @param base64
     * @return
     */
//    public static MultipartFile toMultipart(String base64) {
//        /**
//         *   data:,文本数据
//         data:text/plain,文本数据
//         data:text/html,HTML代码
//         data:text/html;base64,base64编码的HTML代码
//         data:text/css,CSS代码
//         data:text/css;base64,base64编码的CSS代码
//         data:text/javascript,Javascript代码
//         data:text/javascript;base64,base64编码的Javascript代码
//         data:image/gif;base64,base64编码的gif图片数据
//         data:image/png;base64,base64编码的png图片数据
//         data:image/jpeg;base64,base64编码的jpeg图片数据
//         data:image/x-icon;base64,base64编码的icon图片数据
//         */
//        try {
//            String[] baseStrs = base64.split(",");
//
//            BASE64Decoder decoder = new BASE64Decoder();
//            byte[] b = new byte[0];
//            b = decoder.decodeBuffer(baseStrs[1]);
//
//            for (int i = 0; i < b.length; ++i) {
//                if (b[i] < 0) {
//                    b[i] += 256;
//                }
//            }
//
//            return new Base64DecodedMultipartFile(b, baseStrs[0]);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    /**
     * base64转file
     * @param base64
     * @return
     */

    /**
     * base64转化为file流
     * @param base64
     * @return
     */
    public static File base64ToFile(String base64) throws Exception{
        if(base64.contains("data:image")){
            base64 = base64.substring(base64.indexOf(",")+1);
        }
        base64 = base64.toString().replace("\r\n", "");
        //创建文件目录
        String prefix=".jpg";
        File file = File.createTempFile(UUID.randomUUID().toString(), prefix);
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes =  decoder.decodeBuffer(base64);
//       byte[] bytes = Base64.decodeBase64(base64);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        }finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }



    /**
     * 将MultipartFile转换为File
     * @param multiFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     *
     *  file 转成 MultipartFile
     */

    public static MultipartFile getMultipartFile(File file){
        FileInputStream fileInputStream = null;
        MultipartFile multipartFile = null;
        try {
            fileInputStream = new FileInputStream(file);

            multipartFile = new MockMultipartFile(file.getName(),file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        return multipartFile;
    }

    /**
     *  移除文件
     */
    public static void delectFile(String filePath){
        // 移除zip包  TODO 后期优化写成异步的去上文件
        File myObj = new File(filePath);
        // 移除服务器文件
        if(myObj.delete()){
            log.debug("移除文件成功");
        }

    }

    /**
     *
     * @param path  网路路径地址
     * @param desFilePath  文件保存到那个目录下
     * @return 网路url 转成file
     */
    public static Map<String,Object> getNetUrlHttp(String path,String desFilePath){
        Map<String,Object> resultMp = new HashMap<>();
        //对本地文件命名,path是http的完整路径,主要得到资源的名字
        String newUrl = path;
        newUrl = newUrl.split("[?]")[0];
        String[] bb = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = bb[bb.length - 1];
        //保存到本地的路径
        String filePath=desFilePath+fileName;
        resultMp.put("filePath",filePath);
        File file = null;

        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            //判断文件的父级目录是否存在,不存在则创建
            file = new File(filePath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            try{
                //创建文件
                file.createNewFile();
            }catch (Exception e){
                e.printStackTrace();
            }
            //下载
            urlfile = new URL(newUrl);
            inputStream = urlfile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        resultMp.put("file",file);
        return resultMp;
    }

    /**
     * 判断文件大小处于限制内
     *
     * @param fileLen 文件长度
     * @param fileSize 限制大小
     * @param fileUnit 限制的单位(B,K,M,G)
     * @return
     */
    public static boolean checkFileSizeIsLimit(Long fileLen, int fileSize, String fileUnit) {
//        long len = file.length();
        double fileSizeCom = 0;
        if ("B".equals(fileUnit.toUpperCase())) {
            fileSizeCom = (double) fileLen;
        } else if ("K".equals(fileUnit.toUpperCase())) {
            fileSizeCom = (double) fileLen / 1024;
        } else if ("M".equals(fileUnit.toUpperCase())) {
            fileSizeCom = (double) fileLen / (1024*1024);
        } else if ("G".equals(fileUnit.toUpperCase())) {
            fileSizeCom = (double) fileLen / (1024*1024*1024);
        }
        if (fileSizeCom > fileSize) {
            return false;
        }
        return true;

    }

    /**
     * 压缩图片到指定大小
     * @param srcImgData
     * @param reduceMultiple 每次压缩比率
     * @return
     * @throws IOException
     */

    public static byte[] resizeImage(byte[] srcImgData, float reduceMultiple) throws IOException {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData));
        int width = (int) (bi.getWidth() * reduceMultiple); // 源图宽度
        int height = (int) (bi.getHeight() * reduceMultiple); // 源图高度
        Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.setColor(Color.RED);
        g.drawImage(image, 0, 0, null); // 绘制处理后的图
        g.dispose();
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ImageIO.write(tag, "JPEG", bOut);
        return bOut.toByteArray();
    }
    /**
     * byte[]数组转BufferedImage图片流
     */
    public static BufferedImage bytesToBufferedImage(byte[] ImageByte) {
        ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);
        BufferedImage image = null;
        try {
            image = ImageIO.read(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 根据指定大小和指定精度压缩图片
     * @param srcPath
     *            源图片地址
     * @param desPath
     *            目标图片地址
     * @param desFileSize
     *            指定图片大小,单位kb
     * @param accuracy
     *            精度,递归压缩的比率,建议小于0.7
     * @return
     */
//    public static String commpressPicForScale(String srcPath, String desPath,
//                                              long desFileSize, double accuracy) {
//
//        if (!new File(srcPath).exists()) {
//            return null;
//        }
//        try {
//            File srcFile = new File(srcPath);
//            long srcFileSize = srcFile.length();
//            log.debug("源图片:" + srcPath + ",大小:" + srcFileSize / 1024
//                    + "kb");
//
//            // 1、先转换成jpg
//            Thumbnails.of(srcPath).scale(1f).toFile(desPath);
//            // 递归压缩,直到目标文件大小小于desFileSize
//            commpressPicCycle(desPath, desFileSize, accuracy);
//
//            File desFile = new File(desPath);
//            log.debug("目标图片:" + desPath + ",大小" + desFile.length()
//                    / 1024 + "kb");
//            log.info("图片压缩完成!");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        return desPath;
//    }

//    private static void commpressPicCycle(String desPath, long desFileSize,
//                                          double accuracy) throws IOException {
//        File srcFileJPG = new File(desPath);
//        long srcFileSizeJPG = srcFileJPG.length();
//        // 2、判断大小,如果小于500kb,不压缩;如果大于等于500kb,压缩
//        if (srcFileSizeJPG <= desFileSize * 1024) {
//            return;
//        }
//        // 计算宽高
//        BufferedImage bim = ImageIO.read(srcFileJPG);
//        int srcWdith = bim.getWidth();
//        int srcHeigth = bim.getHeight();
//        int desWidth = new BigDecimal(srcWdith).multiply(
//                new BigDecimal(accuracy)).intValue();
//        int desHeight = new BigDecimal(srcHeigth).multiply(
//                new BigDecimal(accuracy)).intValue();
//
//        Thumbnails.of(desPath).size(desWidth, desHeight)
//                .outputQuality(accuracy).toFile(desPath);
//        commpressPicCycle(desPath, desFileSize, accuracy);
//    }


    /**
     * 将pdf文件转成长图片(按指定的页码,注意页码参数下标比实际pdf文件页码小1)
     * @param filePath pdf文件路径
     * @param path 转出图片的路径
     * @param startPage 开始页
     * @param endPage 结束页
     */
//    public static void pdfToHDjpg(String filePath, String path, int startPage, int endPage) {
//        List<BufferedImage> piclist = new ArrayList<>();
//        try (PDDocument document = PDDocument.load(new File(filePath))){
//            PDFRenderer renderer = new PDFRenderer(document);
//            for (int i = 0; i < document.getNumberOfPages(); i++) {
//                if (i >= startPage && i < endPage) {
//                    BufferedImage image = renderer.renderImageWithDPI(i, 96 * 2, ImageType.RGB);
//                    image.flush();
//                    piclist.add(image);
//                }
//            }
//            yPic(piclist, path);
//            piclist.clear();
//        } catch (Exception e1) {
//            // TODO Auto-generated catch block
//            e1.printStackTrace();
//        }finally {
//            piclist.clear();
//
//        }
//    }

    /**
     * 将宽度相同的图片,竖向追加在一起 ##注意:宽度必须相同
     *
     * @param piclist 文件流数组
     * @param outPath 输出路径
     */
    public static void yPic(List<BufferedImage> piclist, String outPath) {// 纵向处理图片
        if (piclist == null || piclist.size() <= 0) {
            log.error("图片数组为空!");
            return;
        }
        try {
            int height = 0, // 总高度
                    width = 0, // 总宽度
                    _height = 0, // 临时的高度 , 或保存偏移高度
                    __height = 0, // 临时的高度,主要保存每个高度
                    picNum = piclist.size();// 图片的数量
            int[] heightArray = new int[picNum]; // 保存每个文件的高度
            BufferedImage buffer = null; // 保存图片流
            List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
            int[] _imgRGB; // 保存一张图片中的RGB数据
            for (int i = 0; i < picNum; i++) {
                buffer = piclist.get(i);
                heightArray[i] = _height = buffer.getHeight();// 图片高度
                if (i == 0) {
                    width = buffer.getWidth();// 图片宽度
                }
                height += _height; // 获取总高度
                _imgRGB = new int[width * _height];// 从图片中读取RGB
                _imgRGB = buffer
                        .getRGB(0, 0, width, _height, _imgRGB, 0, width);
                imgRGB.add(_imgRGB);
            }
            _height = 0; // 设置偏移高度为0
            // 生成新图片
            BufferedImage imageResult = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_BGR);
            for (int i = 0; i < picNum; i++) {
                __height = heightArray[i];
                if (i != 0)
                    _height += __height; // 计算偏移高度
                imageResult.setRGB(0, _height, width, __height, imgRGB.get(i),
                        0, width); // 写入流中
            }
            File outFile = new File(outPath);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(imageResult, "jpg", out);// 写图片
            byte[] b = out.toByteArray();
            FileOutputStream output = new FileOutputStream(outFile);
            output.write(b);
            out.close();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        urlToMultipartFile("https://oss.zhihuixiaoai.com/ffc6c5c007b44cd9b23ac164c45e66f8.JPG");
    }
}
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值